From a84a2aca9d2083474ae90a577d509b8b9dbdc7f0 Mon Sep 17 00:00:00 2001 From: Matthias Kleiner Date: Fri, 27 Nov 2026 11:33:48 +0100 Subject: [PATCH 1/2] SV study: --full-output writes V0s with the raw clusters of their prongs o2-sv-study-workflow --full-output selects K0s, Lambda, anti-Lambda and photon conversions among the V0 finder's V0s and writes them, with everything needed to refit their prongs offline, to o2_v0s_full.root (one entry per TF). New data format DataFormatsGlobalTracking/ TrackV0Extended.h, built like TrackCosmicsExtended.h: - per V0: its two prongs, each with its raw TPC clusters (plus the sharing-map byte), ITS compact clusters and patterns, the matched TOF cluster and the TRD tracklets; the track parameters, times and TOF match of the reconstruction; the assigned primary vertex; selection variables and the downsampling weight - per TF: the TPC transformation info, the TPC occupancy map, the TF ID - with MC input also the MC truth of each prong and of the V0 (common mother of the prongs: PDG code, momentum, production point, its mother), as the kinematics are not kept in MC productions Selection and downsampling (svFullOutput.*, V0FullOutputParams.h): cuts per class, far K0s / Lambda (beyond maxR, both legs without ITS) with their own cuts; flat in log V0 pT per class with a cap per TF and pT bin. Caps >= 1 keep at most int(cap) V0s, caps < 1 keep each V0 with probability cap / candidates (for full passes); the weights restore the spectrum. Random numbers from the TF and the prong tracks. Existing study device: the V0 refit (--refit, or when the finder does not send full V0s) now prepares TPC-only prongs as the V0 finder does (shifted to the vertex time, drift from VDriftHelper), so it reproduces the finder's V0s; svStudy.root changes in refit mode for such V0s. New option --disable-study-tree. calib-workflow.sh: CALIB_ASYNC_EXTRACTV0S=1 runs the extraction in the reconstruction chain (with svertexer.createFullV0s=true the V0s are not refitted). Code review: two rounds by Claude Fable 5.2; all findings addressed. Co-Authored-By: Claude Opus 5.5 --- .../Detectors/GlobalTracking/CMakeLists.txt | 1 + .../TrackV0Extended.h | 228 +++++ .../src/DataFormatsGlobalTrackingLinkDef.h | 13 + .../study/CMakeLists.txt | 4 + .../include/GlobalTrackingStudy/SVStudy.h | 8 +- .../GlobalTrackingStudy/V0FullOutputParams.h | 97 ++ .../study/src/GlobalTrackingStudyLinkDef.h | 2 + .../study/src/SVStudy.cxx | 930 +++++++++++++++++- .../study/src/V0FullOutputParams.cxx | 14 + .../study/src/V0FullWriterSpec.cxx | 46 + .../study/src/sv-study-workflow.cxx | 45 +- prodtests/full-system-test/calib-workflow.sh | 8 + 12 files changed, 1368 insertions(+), 28 deletions(-) create mode 100644 DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/TrackV0Extended.h create mode 100644 Detectors/GlobalTrackingWorkflow/study/include/GlobalTrackingStudy/V0FullOutputParams.h create mode 100644 Detectors/GlobalTrackingWorkflow/study/src/V0FullOutputParams.cxx create mode 100644 Detectors/GlobalTrackingWorkflow/study/src/V0FullWriterSpec.cxx diff --git a/DataFormats/Detectors/GlobalTracking/CMakeLists.txt b/DataFormats/Detectors/GlobalTracking/CMakeLists.txt index 6e7c7025adb18..7540df600dc78 100644 --- a/DataFormats/Detectors/GlobalTracking/CMakeLists.txt +++ b/DataFormats/Detectors/GlobalTracking/CMakeLists.txt @@ -46,4 +46,5 @@ o2_target_root_dictionary( HEADERS include/DataFormatsGlobalTracking/FilteredRecoTF.h include/DataFormatsGlobalTracking/TrackTuneParams.h include/DataFormatsGlobalTracking/TrackCosmicsExtended.h + include/DataFormatsGlobalTracking/TrackV0Extended.h ) diff --git a/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/TrackV0Extended.h b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/TrackV0Extended.h new file mode 100644 index 0000000000000..ab1b970602c9b --- /dev/null +++ b/DataFormats/Detectors/GlobalTracking/include/DataFormatsGlobalTracking/TrackV0Extended.h @@ -0,0 +1,228 @@ +// Copyright 2019-2026 CERN and copyright holders of ALICE O2. +// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +// All rights not expressly granted are reserved. +// +// This software is distributed under the terms of the GNU General Public +// License v3 (GPL Version 3), copied verbatim in the file "COPYING". +// +// In applying this license CERN does 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 TrackV0Extended.h +/// \brief Selected V0s with the raw clusters of their prongs, for offline refits (re-transformation of the clusters with any TPC map) +/// +/// One entry per TF: the selected V0s, each self-contained (as TrackCosmicsExtended): its two prongs with their own raw clusters (with MC +/// input also the MC truth of the prongs and of the V0, as the kinematics are not kept in MC productions). A track +/// used by several V0s of the TF is stored with each of them (TrackV0Extended::nSharedLeg; prong gid identifies it within the TF). Per TF only +/// the TPC transformation info, the TPC occupancy map and the TF ID. Only raw detector data are stored (TPC ClusterNative, ITS compact +/// clusters + patterns, raw TOF time, TRD tracklet words); the TPC transformation, the ITS cluster dictionary and the geometry are applied offline. To reproduce the +/// reconstruction's TPC refit, the per-TF TPC occupancy map (cluster errors) and the cluster sharing-map bytes are stored as well. + +#ifndef ALICEO2_TRACK_V0_EXTENDED_H +#define ALICEO2_TRACK_V0_EXTENDED_H + +#include +#include +#include +#include "ReconstructionDataFormats/V0.h" +#include "ReconstructionDataFormats/GlobalTrackID.h" +#include "ReconstructionDataFormats/Track.h" +#include "DataFormatsTPC/TrackTPC.h" +#include "DataFormatsTPC/ClusterNative.h" +#include "SimulationDataFormat/MCCompLabel.h" + +namespace o2::dataformats +{ + +/// raw TPC cluster attached to a prong's TPC track, with its address +struct V0TPCCluster { + o2::tpc::ClusterNative cl{}; ///< raw cluster: time, pad, widths, charges, flags + uint8_t sector = 0; + uint8_t row = 0; + uint8_t shMap = 0; ///< byte of the reconstruction's TPC cluster sharing map (shared-cluster flags; the sharedmap input of the GPU refit, + ///< which changes the refitted track noticeably) + ClassDefNV(V0TPCCluster, 1); +}; + +/// ITS cluster of a prong: the raw compact cluster (chip, anchor pixel, pattern ID) and its ROF; no coordinates +struct V0ITSCluster { + uint16_t chipID = 0; + uint16_t row = 0; + uint16_t col = 0; + uint16_t pattID = 0; + int32_t pattEntry = -1; ///< start of the pattern bytes in the prong's V0Prong::itsPatterns (pattern not in the dictionary or group pattern), -1: none + int32_t rofBC = 0; ///< start of the cluster's ROF in BCs since the start of the TF + ClassDefNV(V0ITSCluster, 1); +}; + +/// TOF cluster matched to a prong +struct V0TOFCluster { + double timeRaw = 0.; ///< raw TOF time [ps] (the calibration is applied offline) + float tot = 0.f; ///< time over threshold + int32_t channel = -1; + ClassDefNV(V0TOFCluster, 1); +}; + +/// TRD tracklet attached to a prong's TRD track +struct V0TRDTracklet { + uint64_t word = 0; ///< raw Tracklet64 word + int32_t trigBC = 0; ///< BC of its trigger since the start of the TF + uint8_t layer = 0; + ClassDefNV(V0TRDTracklet, 1); +}; + +/// prong track of a V0 with its raw clusters +struct V0Prong { + enum Flags : uint8_t { + HasTPC = 0x1, ///< has a TPC track (tpc is valid, TPC clusters stored) + HasITS = 0x2, ///< has an ITS part (ITS clusters stored) + ITSAB = 0x4, ///< the ITS part is an afterburner tracklet (ITS clusters attached to the TPC track in the ITS-TPC matching), not an ITS track + HasTOF = 0x8, ///< matched to a TOF cluster (stored) + HasTRD = 0x10 ///< has a TRD track (its tracklets stored) + }; + GlobalTrackID gid{}; ///< global track ID of the prong (only valid within the TF) + o2::track::TrackParCov track{}; ///< global track parameters (inner point of the track); a TPC-only track at its time0, not + ///< shifted to the vertex time as in the V0 (TrackV0Extended::v0 prongs) + o2::tpc::TrackTPC tpc{}; ///< TPC-only track (default if none); z refers to its time0; its cluster references are only valid + ///< within the TF: the clusters are in clTPC + float timeMUS = 0.f; ///< time of the global track [mus since the TF start] + float timeErrMUS = 0.f; ///< its error [mus] + float chi2ITSTPC = -1.f; ///< chi2 of the ITS-TPC match (< 0: no ITS-TPC match) + std::vector clTPC; ///< TPC clusters of the TPC track, in the order of its cluster references + std::vector clITS; ///< ITS clusters of the ITS track or of the afterburner tracklet + std::vector itsPatterns; ///< pattern bytes (row span, column span, bitmap) of the ITS clusters that need them + std::vector clTOF; ///< the matched TOF cluster (0 or 1) + std::vector trdTracklets; ///< TRD tracklets of the TRD track + uint8_t flags = 0; ///< Flags + // TOF match of the reconstruction (HasTOF), for TOF PID: beta = tofLength / (c (tofSignal - TrackV0Extended::evTimeTOF)) + double tofSignal = 0.; ///< calibrated TOF time of the match [ps since the TF start] (MatchInfoTOF::getSignal) + float tofLength = 0.f; ///< integrated track length to the TOF cluster [cm] as in the reconstruction: tracks with ITS from their + ///< closest approach to the beam line (as for a primary track), the others from their start + float tofExpTime[5] = {0.f}; ///< expected times of flight [ps] for e, mu, pi, K, p (o2::track::PID 0-4) over tofLength + o2::MCCompLabel mcLabel{}; ///< MC label of the global track (MC input only; else not set) + // MC truth of the particle of mcLabel, stored because the kinematics are not kept in MC productions (MC input only) + int mcPDG = 0; ///< its PDG code (0: no MC particle) + float mcP[3] = {0.f}; ///< its momentum at its production [GeV] (px, py, pz) + float mcVtx[3] = {0.f}; ///< its production point [cm] (for a prong of a true V0: the true decay / conversion point) + bool hasTPC() const { return flags & HasTPC; } + bool hasITS() const { return flags & HasITS; } + bool isITSAB() const { return flags & ITSAB; } + bool hasTOF() const { return flags & HasTOF; } + bool hasTRD() const { return flags & HasTRD; } + ClassDefNV(V0Prong, 1); +}; + +/// selected V0 with its selection variables +struct TrackV0Extended { + enum Selection : uint8_t { + K0 = 0x1, ///< passed the K0s selection + Lambda = 0x2, ///< passed the Lambda selection (proton = positive prong) + AntiLambda = 0x4, ///< passed the anti-Lambda selection + PhotonOnly = 0x8, ///< the V0 finder flagged the candidate as photon only (V0Index::isPhotonOnly) + Gamma = 0x10, ///< passed the photon-conversion selection + BestForLegs = 0x20, ///< best V0 for its tracks: greedy matching over the selected V0s of the TF, each track in at most one, lowest + ///< w 60 acos(cosPA) + (1 - w) sqrt(dca) / 3 cm first (w = svFullOutput.legScoreWeight) + Far = 0x40 ///< selected with the far cuts (svFullOutput.*Far): beyond maxR, both legs without ITS + }; + enum SampleClass : uint8_t { ClassK0 = 0, + ClassLambda = 1, + ClassAntiLambda = 2, + ClassGamma = 3 }; + V0 v0{}; ///< the V0 finder's V0 if it sent them (svertexer.createFullV0s), else the study device's refit (DCAFitter with + ///< the V0 finder's settings and prong preparation: TPC-only prongs shifted to the vertex time); prongs at the decay vertex + V0Prong prongPos{}; ///< positive prong with its clusters (gid: the V0 finder's prong ID) + V0Prong prongNeg{}; ///< negative prong + float dca = 0.f; ///< V0::getDCA of the refit (chi2 at the point of closest approach of the prongs, as cut in the V0 finder) + float cosPA = 0.f; ///< cosine of the pointing angle to the primary vertex + float qT = 0.f; ///< Armenteros qT [GeV] + float alpha = 0.f; ///< Armenteros alpha + float r = 0.f; ///< transverse decay radius [cm] + float massK0 = 0.f; ///< invariant mass as pi+ pi- [GeV] + float massLambda = 0.f; ///< as p pi- [GeV] + float massAntiLambda = 0.f; ///< as pbar pi+ [GeV] + float massGamma = 0.f; ///< as e+ e- [GeV] + float tpcOccBef = 0.f; ///< TPC clusters before the time of the primary vertex, as tpcOccBef in svStudy.root (0: no occupancy map) + float tpcOccAft = 0.f; ///< same after + uint8_t selection = 0; ///< Selection bits + uint8_t sampleClass = 0; ///< SampleClass of the downsampling (first passed type of K0s, Lambda, anti-Lambda, photon) + float weight = 1.f; ///< downsampling weight: V0s of its class (far ones apart: bit Far) and pT bin in the TF / kept ones, or / the cap + ///< svFullOutput.maxPerBin* if below 1 (1: all kept) + float pvX = 0.f; ///< primary vertex the V0 finder assigned [cm] + float pvY = 0.f; + float pvZ = 0.f; + float pvTimeMUS = 0.f; ///< its time [mus since the TF start] + float pvTimeErrMUS = 0.f; ///< and the time error + int pvNContrib = 0; ///< its number of contributors + int nCompatPV = 0; ///< primary vertices of the TF compatible in time with both prongs (TPC-only prong: its TPC time window; + ///< else its time +- svFullOutput.pvTimeNSigma errors): 1 = unique, e.g. the z of TPC-only photon legs + ///< from the vertex time + int nPairPV = 1; ///< primary vertices the V0 finder built this prong pair with (TPC-only prongs: one copy per vertex, shifted + ///< in z to its time); only the copy with the largest cosPA is written (this one) + float cosPA2 = -2.f; ///< cosPA of the copy with the second-largest cosPA (-2: no other copy) + int nSharedLeg = 0; ///< other selected V0s of the TF (any class, before the downsampling) using one of its tracks (stored with each) + + float pvCov[6] = {0.f}; ///< position covariance of the assigned primary vertex [cm^2] (VertexBase order: xx, xy, yy, xz, yz, zz) + float legDCAxy[2] = {-999.f, -999.f}; ///< DCA of the positive / negative leg to that vertex in the bending plane [cm] (the V0's prong + ///< propagated from the decay vertex, TPC-only legs in z shifted to the vertex time; -999: failed) + float legDCAz[2] = {-999.f, -999.f}; ///< same along z [cm] + double evTimeTOF = 0.; ///< event time of that vertex from its TOF-matched tracks [ps since the TF start]: robust mean of + ///< (TOF signal - expected pion time), the V0's own legs excluded (evTimeTOFN = 0: none) + float evTimeTOFErr = 0.f; ///< its error [ps] (spread / sqrt(N)) + int evTimeTOFN = 0; ///< TOF tracks used + // MC truth of the V0 (MC input only): the common mother of the two prongs, if they are two different particles of one source and event + // with the same mother, each from a decay or pair production, produced at one point >= 1 um away from where the mother was produced, + // and the mother is not a beam particle (see SVStudy setV0Truth). Short-lived species decayed by the generator can pass: check mcPDG + o2::MCCompLabel mcLabel{}; ///< the common mother (invalid: none, e.g. a combinatorial V0; the prongs' mcLabel keep their fake flags) + int mcPDG = 0; ///< its PDG code (0: no common mother) + float mcP[3] = {0.f}; ///< its momentum at its production [GeV] (px, py, pz) + float mcVtx[3] = {0.f}; ///< its production point [cm]: the primary vertex, or the decay point of its own mother (feed-down) + int mcMotherPDG = 0; ///< PDG code of the mother of the common mother (e.g. 311 for a K0s, 111 for a photon from a pi0, 3312 for a Lambda from a Xi-; 0: none) + bool mcPrimary = false; ///< the common mother comes from the generator (MCTrack::isPrimary, incl. generator decays), not from the transport + + const V0Prong& prong(int ip) const { return ip == 0 ? prongPos : prongNeg; } ///< 0: positive, 1: negative (as V0::getProng) + V0Prong& prong(int ip) { return ip == 0 ? prongPos : prongNeg; } + + // decay-tagged species (no data member: follows from selection and the prong order), e.g. TTree::Draw selections "v0s.isLambda()", + // "v0s.legPID(0)==4" (protons of Lambda decays) + static constexpr uint8_t TypeBits = K0 | Lambda | AntiLambda | Gamma; + bool isK0() const { return (selection & TypeBits) == K0; } ///< K0s and no other type (far V0s included: isFar()) + bool isLambda() const { return (selection & TypeBits) == Lambda; } ///< Lambda and no other type + bool isAntiLambda() const { return (selection & TypeBits) == AntiLambda; } ///< anti-Lambda and no other type + bool isGamma() const { return (selection & TypeBits) == Gamma; } ///< photon conversion and no other type + bool isFar() const { return selection & Far; } + bool isBestForLegs() const { return selection & BestForLegs; } + bool isMCTrue() const { return mcLabel.isValid(); } ///< MC: both prongs come from the displaced decay / conversion of one MC particle + /// species of prong ip (0 positive, 1 negative) from the decay, as o2::track::PID::ID (0 e, 2 pi, 4 p): K0s pi+ pi-, Lambda p pi-, + /// anti-Lambda pi+ pbar, photon e+ e-; -1 if not exactly one type bit is set (far V0s in the wide K0s and Lambda windows can have two) + int legPID(int ip) const + { + switch (selection & TypeBits) { + case K0: + return o2::track::PID::Pion; + case Lambda: + return ip == 0 ? o2::track::PID::Proton : o2::track::PID::Pion; + case AntiLambda: + return ip == 0 ? o2::track::PID::Pion : o2::track::PID::Proton; + case Gamma: + return o2::track::PID::Electron; + default: + return -1; + } + } + ClassDefNV(TrackV0Extended, 1); +}; + +/// per-TF quantities: the TPC transformation used in the reconstruction and the TPC occupancy +struct V0sTFInfo { + float vDrift = 0.f; ///< drift velocity of the transformation [cm/time bin] + float t0 = 0.f; ///< time offset of the transformation [time bins] + float lumi = 0.f; ///< luminosity estimator the map was scaled with (TPCFastTransformPOD::getLumi) + float idc = 0.f; ///< IDC estimator the map was scaled with (TPCFastTransformPOD::getIDC); TPC occupancy: branch tpcOccMap; the + ///< refit with it also needs the HBFs per TF (GRPECSObject::getNHBFPerTF of the run) + ClassDefNV(V0sTFInfo, 1); +}; + +} // namespace o2::dataformats + +#endif diff --git a/DataFormats/Detectors/GlobalTracking/src/DataFormatsGlobalTrackingLinkDef.h b/DataFormats/Detectors/GlobalTracking/src/DataFormatsGlobalTrackingLinkDef.h index 06d54368484d0..5177149caddac 100644 --- a/DataFormats/Detectors/GlobalTracking/src/DataFormatsGlobalTrackingLinkDef.h +++ b/DataFormats/Detectors/GlobalTracking/src/DataFormatsGlobalTrackingLinkDef.h @@ -34,4 +34,17 @@ #pragma link C++ class std::vector < o2::dataformats::TrackCosmicsExtended> + ; #pragma link C++ class o2::dataformats::CosmicsTFInfo + ; +#pragma link C++ class o2::dataformats::V0TPCCluster + ; +#pragma link C++ class std::vector < o2::dataformats::V0TPCCluster> + ; +#pragma link C++ class o2::dataformats::V0ITSCluster + ; +#pragma link C++ class std::vector < o2::dataformats::V0ITSCluster> + ; +#pragma link C++ class o2::dataformats::V0TOFCluster + ; +#pragma link C++ class std::vector < o2::dataformats::V0TOFCluster> + ; +#pragma link C++ class o2::dataformats::V0TRDTracklet + ; +#pragma link C++ class std::vector < o2::dataformats::V0TRDTracklet> + ; +#pragma link C++ class o2::dataformats::V0Prong + ; +#pragma link C++ class o2::dataformats::TrackV0Extended + ; +#pragma link C++ class std::vector < o2::dataformats::TrackV0Extended> + ; +#pragma link C++ class o2::dataformats::V0sTFInfo + ; + #endif diff --git a/Detectors/GlobalTrackingWorkflow/study/CMakeLists.txt b/Detectors/GlobalTrackingWorkflow/study/CMakeLists.txt index bfb167f2cc6dd..e5813964f8c6e 100644 --- a/Detectors/GlobalTrackingWorkflow/study/CMakeLists.txt +++ b/Detectors/GlobalTrackingWorkflow/study/CMakeLists.txt @@ -28,6 +28,8 @@ o2_add_library(GlobalTrackingStudy src/CheckResidSpec.cxx src/CheckResidConfig.cxx src/HistoManager.cxx + src/V0FullOutputParams.cxx + src/V0FullWriterSpec.cxx PUBLIC_LINK_LIBRARIES O2::GlobalTracking O2::GlobalTrackingWorkflowReaders O2::GlobalTrackingWorkflowHelpers @@ -38,6 +40,7 @@ o2_add_library(GlobalTrackingStudy O2::DataFormatsTRD O2::DataFormatsTOF O2::TPCWorkflow + O2::DPLUtils O2::SimulationDataFormat) o2_target_root_dictionary(GlobalTrackingStudy @@ -48,6 +51,7 @@ o2_target_root_dictionary(GlobalTrackingStudy include/GlobalTrackingStudy/CheckResidTypes.h include/GlobalTrackingStudy/CheckResidConfig.h include/GlobalTrackingStudy/HistoManager.h + include/GlobalTrackingStudy/V0FullOutputParams.h LINKDEF src/GlobalTrackingStudyLinkDef.h ) diff --git a/Detectors/GlobalTrackingWorkflow/study/include/GlobalTrackingStudy/SVStudy.h b/Detectors/GlobalTrackingWorkflow/study/include/GlobalTrackingStudy/SVStudy.h index d54513cb07a60..513a656a51d5f 100644 --- a/Detectors/GlobalTrackingWorkflow/study/include/GlobalTrackingStudy/SVStudy.h +++ b/Detectors/GlobalTrackingWorkflow/study/include/GlobalTrackingStudy/SVStudy.h @@ -21,8 +21,12 @@ namespace o2::svstudy { -/// create a processor spec -o2::framework::DataProcessorSpec getSVStudySpec(o2::dataformats::GlobalTrackID::mask_t srcTracks, o2::dataformats::GlobalTrackID::mask_t srcCls, bool useMC); +/// create a processor spec; fullOutput: also send the selected V0s with the raw clusters of their prongs (TrackV0Extended.h, see +/// V0FullOutputParams for the selection), written by getV0FullWriterSpec +o2::framework::DataProcessorSpec getSVStudySpec(o2::dataformats::GlobalTrackID::mask_t srcTracks, o2::dataformats::GlobalTrackID::mask_t srcCls, bool useMC, bool fullOutput = false); + +/// writer of the --full-output V0s to o2_v0s_full.root +o2::framework::DataProcessorSpec getV0FullWriterSpec(); } // namespace o2::svstudy diff --git a/Detectors/GlobalTrackingWorkflow/study/include/GlobalTrackingStudy/V0FullOutputParams.h b/Detectors/GlobalTrackingWorkflow/study/include/GlobalTrackingStudy/V0FullOutputParams.h new file mode 100644 index 0000000000000..59a4963be7d64 --- /dev/null +++ b/Detectors/GlobalTrackingWorkflow/study/include/GlobalTrackingStudy/V0FullOutputParams.h @@ -0,0 +1,97 @@ +// Copyright 2019-2026 CERN and copyright holders of ALICE O2. +// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +// All rights not expressly granted are reserved. +// +// This software is distributed under the terms of the GNU General Public +// License v3 (GPL Version 3), copied verbatim in the file "COPYING". +// +// In applying this license CERN does 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 V0FullOutputParams.h +/// \brief Selection and downsampling of the V0s written with their clusters by o2-sv-study-workflow --full-output + +#ifndef O2_SV_STUDY_V0_FULL_OUTPUT_PARAMS_H +#define O2_SV_STUDY_V0_FULL_OUTPUT_PARAMS_H + +#include "CommonUtils/ConfigurableParam.h" +#include "CommonUtils/ConfigurableParamHelper.h" + +namespace o2::svstudy +{ +/// Prong cuts are applied before the refit of a candidate (they need only its tracks), V0 cuts after it. A V0 passing the cuts of a type +/// (K0s, Lambda, anti-Lambda, photon) is assigned to one sampling class (in this order of priority); the types it passed are flagged in +/// TrackV0Extended::selection. Per TF and class the V0s are then sampled flat in V0 pT, in nPtBins log bins between ptMin and ptMax (plus +/// one bin below and one above), at random (reproducible: hash of the TF and the two prong tracks). The cap maxPerBin* is the number of V0s kept +/// per TF and bin: cap >= 1: at most int(cap) V0s, weight (V0s of its class and bin) / (kept ones); 0 <= cap < 1: on average cap V0s, +/// each V0 kept with probability cap / (V0s of its class and bin), weight (V0s of its class and bin) / cap (e.g. for a full +/// reconstruction pass: about one V0 per TF and class with caps of 0.05-0.08); < 0: all kept. Far V0s (bit Far) are sampled apart from +/// the others of their class, with maxPerBinFar (default: all kept). With caps >= 1 the V0s written per TF that are not far are at +/// most (nPtBins + 2) (maxPerBinK0 + 2 maxPerBinLambda + maxPerBinGamma) (440 with the defaults). +struct V0FullOutputParams : o2::conf::ConfigurableParamHelper { + // prong cuts, before the refit + bool requireOppositeCharges = true; ///< prongs of opposite charge + bool requireTPCBoth = true; ///< both prongs with a TPC track + int minTPCClusters = 0; ///< min. number of TPC clusters of each prong (if it has a TPC track) + // V0 cuts for K0s and Lambda, after the refit + float maxDCA = 0.01f; ///< max. V0::getDCA (chi2 at the point of closest approach of the prongs) + float minCosPA = 0.9998f; ///< min. cosine of the pointing angle to the primary vertex + float minQt = 0.01f; ///< min. Armenteros qT [GeV] + float maxQt = 0.25f; ///< max. Armenteros qT [GeV] (above the K0s endpoint 0.206 GeV) + float minR = 5.f; ///< min. transverse decay radius [cm] + float maxR = 35.f; ///< max. transverse decay radius [cm] + bool selK0 = true; ///< select K0s + float maxDMassK0 = 0.010f; ///< max. |m(pi+ pi-) - m(K0s)| [GeV] + float vetoDMassLambdaK0 = 0.005f; ///< K0s within maxR: not a K0s if |m(p pi-) - m(Lambda)| or |m(pbar pi+) - m(Lambda)| is below this [GeV] + ///< (the Lambda reflection where the K0s and Lambda ellipses cross; < 0: no veto). Far K0s: minQtK0Far + bool selLambda = true; ///< select Lambda and anti-Lambda + float maxDMassLambda = 0.005f; ///< max. |m(p pi) - m(Lambda)| [GeV] + float minAlphaLambda = 0.28f; ///< min. Armenteros alpha of a Lambda (anti-Lambda: max. -minAlphaLambda) + float maxAlphaLambda = 0.95f; ///< max. Armenteros alpha of a Lambda (anti-Lambda: min. -maxAlphaLambda); 0.95: the whole Lambda ellipse + float vetoDMassK0Lambda = 0.005f; ///< Lambda / anti-Lambda within maxR: not a Lambda if |m(pi+ pi-) - m(K0s)| is below this [GeV] (the K0s + ///< reflection where the two ellipses cross, |alpha| 0.7-0.85; < 0: no veto) + // far K0s and Lambda: beyond maxR, both legs without ITS, with these cuts instead of the ones above. + // Defaults tuned on Pb-Pb data with mass sidebands + bool selFar = true; ///< select far K0s / Lambda + float maxRFar = 250.f; ///< max. transverse decay radius [cm] of far V0s + float maxDCAFar = 0.1f; ///< max. V0::getDCA of far V0s + float minQtFar = 0.06f; ///< min. Armenteros qT [GeV] of far V0s (the background piles up at low qT) + float minQtK0Far = 0.105f; ///< min. Armenteros qT [GeV] of far K0s: above the Lambda maximum (0.101 GeV), removes the Lambda + ///< reflection in the K0s window; keeps the K0s decays with |cos(theta*)| < ~0.86 + float minCosPAFar = 0.9998f; ///< min. cosine of the pointing angle of far V0s + int minTPCClustersFar = 80; ///< min. number of TPC clusters of each leg of a far V0 (short background legs) + float maxCtK0Far = 20.f; ///< max. proper decay length L m / p [cm] of far K0s (L: 3D distance from the primary vertex; c tau 2.68 cm) + float maxCtLambdaFar = 40.f; ///< max. proper decay length L m / p [cm] of far Lambdas (c tau 7.89 cm) + float maxDMassK0Far = 0.03f; ///< max. |m(pi+ pi-) - m(K0s)| [GeV] of far V0s (their peak is wider and lower than the inner one) + float maxDMassLambdaFar = 0.01f; ///< max. |m(p pi) - m(Lambda)| [GeV] of far V0s + float maxAlphaLambdaFar = 0.7f; ///< max. Armenteros alpha of a far Lambda (anti-Lambda: min. -maxAlphaLambdaFar) + // photon conversions, after the refit (only these cuts apply to them) + bool selGamma = true; ///< select photon conversions: V0 finder's photon-only flag or m(e+ e-) < maxMassGamma + float maxMassGamma = 0.05f; ///< max. m(e+ e-) [GeV] + float maxQtGamma = 0.01f; ///< Armenteros cut as the O2Physics photon-conversion-builder: (alpha / maxAlphaGamma)^2 + (qT / maxQtGamma)^2 + ///< < 1, maxQtGamma [GeV] + float maxAlphaGamma = 0.95f; ///< alpha of that ellipse + float minLegDCAXYGamma = 0.1f; ///< min. |DCA_xy| [cm] of both legs to the primary vertex, as in O2Physics (< 0: no cut; a leg whose propagation + ///< to the vertex fails passes) + float minRGamma = 1.f; ///< min. transverse conversion radius [cm] + float maxRGamma = 90.f; ///< max. transverse conversion radius [cm] (TPC inner field cage) + float minCosPAGamma = 0.99f; ///< min. cosine of the pointing angle (loose: the photon pointing is an observable) + float maxDCAGamma = -1.f; ///< max. V0::getDCA (< 0: no cut beyond the V0 finder's) + // downsampling flat in V0 pT, per class (< 0: keep all) + int nPtBins = 20; ///< log V0-pT bins between ptMin and ptMax + float ptMin = 0.1f; ///< [GeV] + float ptMax = 10.f; ///< [GeV] + float maxPerBinK0 = 5.f; ///< K0s kept per TF and pT bin (< 1: on average) + float maxPerBinLambda = 5.f; ///< Lambdas kept per TF and pT bin, and the same for the anti-Lambdas + float maxPerBinGamma = 5.f; ///< photons kept per TF and pT bin + float maxPerBinFar = -1.f; ///< far K0s / Lambdas (bit Far) kept per TF and pT bin, sampled apart from the other V0s of their class (< 0: all) + float pvTimeNSigma = 4.f; ///< nCompatPV: primary vertices within this many sigma of their time error of the prongs' time windows + float legScoreWeight = 0.f; ///< weight of the pointing angle in legScore (1 - weight: leg distance), as deduplicationScoreWeight in O2Physics + ///< (0.5 there); 0: the leg distance alone + + O2ParamDef(V0FullOutputParams, "svFullOutput"); +}; +} // namespace o2::svstudy + +#endif diff --git a/Detectors/GlobalTrackingWorkflow/study/src/GlobalTrackingStudyLinkDef.h b/Detectors/GlobalTrackingWorkflow/study/src/GlobalTrackingStudyLinkDef.h index b1fe732fbefc4..10c33e5487c7a 100644 --- a/Detectors/GlobalTrackingWorkflow/study/src/GlobalTrackingStudyLinkDef.h +++ b/Detectors/GlobalTrackingWorkflow/study/src/GlobalTrackingStudyLinkDef.h @@ -48,6 +48,8 @@ #pragma link C++ class o2::checkresid::Track + ; #pragma link C++ class o2::checkresid::CheckResidConfig + ; #pragma link C++ class o2::conf::ConfigurableParamHelper < o2::checkresid::CheckResidConfig> + ; +#pragma link C++ class o2::svstudy::V0FullOutputParams + ; +#pragma link C++ class o2::conf::ConfigurableParamHelper < o2::svstudy::V0FullOutputParams> + ; #pragma link C++ class o2::HistoManager + ; diff --git a/Detectors/GlobalTrackingWorkflow/study/src/SVStudy.cxx b/Detectors/GlobalTrackingWorkflow/study/src/SVStudy.cxx index ed0dbc3829cc5..a8fc02fbe3169 100644 --- a/Detectors/GlobalTrackingWorkflow/study/src/SVStudy.cxx +++ b/Detectors/GlobalTrackingWorkflow/study/src/SVStudy.cxx @@ -11,6 +11,10 @@ #include #include +#include +#include +#include +#include #include "DataFormatsGlobalTracking/RecoContainer.h" #include "DataFormatsGlobalTracking/RecoContainerCreateTracksVariadic.h" #include "DetectorsVertexing/SVertexerParams.h" @@ -41,9 +45,36 @@ #include "ReconstructionDataFormats/VtxTrackRef.h" #include "ReconstructionDataFormats/DCA.h" #include "Steer/MCKinematicsReader.h" +#include "SimulationDataFormat/MCGenProperties.h" #include "DCAFitter/DCAFitterN.h" #include "MathUtils/fit.h" #include "GlobalTrackingStudy/V0Ext.h" +#include "GlobalTrackingStudy/V0FullOutputParams.h" +#include "DataFormatsGlobalTracking/TrackV0Extended.h" +#include "DataFormatsITS/TrackITS.h" +#include "DataFormatsITSMFT/CompCluster.h" +#include "DataFormatsITSMFT/ROFRecord.h" +#include "DataFormatsITSMFT/TopologyDictionary.h" +#include "DataFormatsITSMFT/ClusterPattern.h" +#include "DataFormatsTOF/Cluster.h" +#include "DataFormatsTRD/TrackTRD.h" +#include "DataFormatsTRD/Tracklet64.h" +#include "DataFormatsTRD/TriggerRecord.h" +#include "CommonDataFormat/TFIDInfo.h" +#include "CommonConstants/PhysicsConstants.h" +#include "DetectorsBase/TFIDInfoHelper.h" +#include "TPCFastTransformPOD.h" +#include "TPCCalibration/VDriftHelper.h" +#include "CommonConstants/LHCConstants.h" +#include "MathUtils/Utils.h" +#include "CommonDataFormat/InteractionRecord.h" +#include +#include +#include +#include +#include +#include +#include #include "GPUO2InterfaceConfiguration.h" // #include "GPUSettingsO2.h" #include "GPUParam.h" @@ -71,8 +102,8 @@ using timeEst = o2::dataformats::TimeStampWithError; class SVStudySpec final : public Task { public: - SVStudySpec(std::shared_ptr dr, std::shared_ptr gr, GTrackID::mask_t src, bool useTPCCl, bool useMC) - : mDataRequest(dr), mGGCCDBRequest(gr), mTracksSrc(src), mUseTPCCl(useTPCCl), mUseMC(useMC) {} + SVStudySpec(std::shared_ptr dr, std::shared_ptr gr, GTrackID::mask_t src, bool useTPCCl, bool useMC, bool fullOutput) + : mDataRequest(dr), mGGCCDBRequest(gr), mTracksSrc(src), mUseTPCCl(useTPCCl), mUseMC(useMC), mFullOutput(fullOutput) {} ~SVStudySpec() final = default; void init(InitContext& ic) final; void run(ProcessingContext& pc) final; @@ -82,8 +113,34 @@ class SVStudySpec final : public Task o2::dataformats::V0Ext processV0(int iv, o2::globaltracking::RecoContainer& recoData); private: + /// ITS cluster of the full output whose pattern bytes are in the TF's pattern stream + struct ITSPattRequest { + int prong; ///< entry of the prong in FullOutput::prongs + int cluster; ///< entry of the cluster in its clITS + int index; ///< index of the cluster in the TF + }; + /// output of --full-output for one TF + struct FullOutput { + std::vector v0s; + std::vector> v0Prongs; ///< entries of the positive / negative prong of each V0 in prongs + std::vector prongs; ///< each track once (with its clusters), copied into its V0s at the end of the TF + std::unordered_map prongEntry; ///< prong entry of a global track ID (GTrackID::getRawWOFlags) + std::vector pattRequests; + }; + void updateTimeDependentParams(ProcessingContext& pc); bool refitV0(const V0ID& id, o2::dataformats::V0& v0, o2::globaltracking::RecoContainer& recoData); + o2::track::TrackParCov getProngSeed(GTrackID gid, int vtxID, const o2::globaltracking::RecoContainer& recoData) const; + const o2::dataformats::V0* getV0(int iv, o2::globaltracking::RecoContainer& recoData); + void getTPCOccupancy(const PVertex& pv, float& occBef, float& occAft) const; + void processFull(o2::globaltracking::RecoContainer& recoData, ProcessingContext& pc); + bool passProngCuts(const V0ID& id, const o2::globaltracking::RecoContainer& recoData) const; + bool passFarLegCuts(const V0ID& id, const o2::globaltracking::RecoContainer& recoData) const; + int countCompatiblePVs(const V0ID& id, const o2::globaltracking::RecoContainer& recoData) const; + int addProng(GTrackID gid, const o2::globaltracking::RecoContainer& recoData, FullOutput& out); + const o2::MCTrack* getMCTrack(int source, int event, int track) const; + void setV0Truth(o2::dataformats::TrackV0Extended& v0, const o2::dataformats::V0Prong& pos, const o2::dataformats::V0Prong& neg) const; + void fillITSPatterns(const o2::globaltracking::RecoContainer& recoData, FullOutput& out) const; std::shared_ptr mDataRequest; std::shared_ptr mGGCCDBRequest; bool mUseMC{false}; ///< MC flag @@ -91,28 +148,63 @@ class SVStudySpec final : public Task float mSelK0 = -1; bool mRefit = false; bool mUseTPCCl = false; + bool mStudyTree = true; ///< write svStudy.root + bool mFullOutput = false; ///< send the selected V0s with the raw clusters of their prongs + std::vector mRefitV0s; ///< refitted V0s of the TF (index = V0 finder entry), shared by svStudy.root and the full output + std::vector mRefitStatus; ///< per V0 finder entry: -1 not refitted yet, 0 refit failed, 1 refitted + const o2::gpu::TPCFastTransformPOD* mCorrMap = nullptr; ///< TPC transformation of the TF (full output) + const o2::itsmft::TopologyDictionary* mITSDict = nullptr; ///< ITS cluster dictionary (full output: which patterns to store) + o2::InteractionRecord mTFStart{}; ///< first BC of the TF + mutable bool mNoDictWarned = false; + size_t mNV0sFull = 0; ///< V0s written with clusters + size_t mNProngsFull = 0; ///< distinct prong tracks written + size_t mNClTPCFull = 0; ///< TPC clusters written (a track shared by several V0s once per V0) float mMaxEta = 0.8; float mBz = 0; int mNHBPerTF = 0; int mNTPCOccBinLength = 0; ///< TPC occ. histo bin length in TBs - float mNTPCOccBinLengthInv; + float mNTPCOccBinLengthInv = 0.f; float mTPCTBinMUSInv = 0.f; + float mTPCTBinMUS = 0.f; + float mTPCBin2Z = 0.f; ///< drift [cm] per TPC time bin of 8 BCs, as in the V0 finder (TPC-only prongs of a refit) + o2::tpc::VDriftHelper mTPCVDriftHelper{}; ///< TPC drift velocity as in the V0 finder GTrackID::mask_t mTracksSrc{}; o2::vertexing::DCAFitterN<2> mFitterV0; std::vector mTBinClOccAft, mTBinClOccBef; std::unique_ptr mcReader; // reader of MC information + mutable bool mMCWarned = false; ///< a failed MC lookup was reported + std::set> mMCEventsTF; ///< MC (source, event) looked up in the TF, released at its end std::shared_ptr mParam = nullptr; }; void SVStudySpec::init(InitContext& ic) { o2::base::GRPGeomHelper::instance().setRequest(mGGCCDBRequest); - mDBGOut = std::make_unique("svStudy.root", "recreate"); + mStudyTree = !ic.options().get("disable-study-tree"); + if (mStudyTree) { + mDBGOut = std::make_unique("svStudy.root", "recreate"); + } mRefit = ic.options().get("refit"); mSelK0 = ic.options().get("sel-k0"); mMaxEta = ic.options().get("max-eta"); if (mUseMC) { + // MC truth needs the collision context and the kinematics of every source in the working directory; without them only the labels mcReader = std::make_unique("collisioncontext.root"); + bool mcOK = mcReader->isInitialized() && mcReader->getDigitizationContext(); + if (mcOK) { + for (const auto& prefix : mcReader->getDigitizationContext()->getSimPrefixes()) { + const auto kineName = o2::base::NameConf::getMCKinematicsFileName(prefix); + std::unique_ptr kine(gSystem->AccessPathName(kineName.c_str()) ? nullptr : TFile::Open(kineName.c_str())); + auto kineTree = (kine && !kine->IsZombie()) ? dynamic_cast(kine->Get("o2sim")) : nullptr; + if (!kineTree || !kineTree->GetBranch("MCTrack")) { + mcOK = false; + } + } + } + if (!mcOK) { + LOGP(warning, "MC: no collisioncontext.root or kinematics files in the working directory, MC labels without the MC truth"); + mcReader.reset(); + } } } @@ -163,7 +255,27 @@ void SVStudySpec::run(ProcessingContext& pc) } } - process(recoData); + // the V0 finder sends only the V0 indices unless svertexer.createFullV0s: then every V0 is refitted, once per TF for both outputs + const auto nv0 = recoData.getV0sIdx().size(); + if (nv0 > recoData.getV0s().size()) { + mRefit = true; + } + if (mRefit) { + mRefitStatus.assign(nv0, -1); + mRefitV0s.resize(nv0); + } + + if (mStudyTree) { + process(recoData); + } + if (mFullOutput) { + processFull(recoData, pc); + } + // the MC reader keeps every event it loaded: release those of this TF (both outputs; a later TF reloads them if needed) + for (const auto& [src, ev] : mMCEventsTF) { + mcReader->releaseTracksForSourceAndEvent(src, ev); + } + mMCEventsTF.clear(); } void SVStudySpec::updateTimeDependentParams(ProcessingContext& pc) @@ -197,10 +309,23 @@ void SVStudySpec::updateTimeDependentParams(ProcessingContext& pc) mParam = o2::gpu::GPUO2InterfaceUtils::getFullParamShared(0.f, mNHBPerTF); } auto& elParam = o2::tpc::ParameterElectronics::Instance(); + mTPCTBinMUS = elParam.ZbinWidth; mTPCTBinMUSInv = 1. / elParam.ZbinWidth; // 1./TPC bin in microseconds } + if (mTracksSrc[GTrackID::TPC]) { // drift velocity for the TPC-only prongs of a refit, requested only with TPC tracks (as in the V0 finder) + mTPCVDriftHelper.extractCCDBInputs(pc); + if (mTPCVDriftHelper.isUpdated()) { + // same float arithmetic as SVertexer::setTPCVDrift / setTPCTBin + const float mus2TB = 1.f / (8 * o2::constants::lhc::LHCBunchSpacingMUS); + mTPCBin2Z = mTPCVDriftHelper.getVDriftObject().getVDrift() / mus2TB; + mTPCVDriftHelper.acknowledgeUpdate(); + } + } mBz = o2::base::Propagator::Instance()->getNominalBz(); mFitterV0.setBz(mBz); + if (mFullOutput) { + mCorrMap = &o2::gpu::TPCFastTransformPOD::get(pc.inputs().get("corrMap")); + } } o2::dataformats::V0Ext SVStudySpec::processV0(int iv, o2::globaltracking::RecoContainer& recoData) @@ -213,9 +338,13 @@ o2::dataformats::V0Ext SVStudySpec::processV0(int iv, o2::globaltracking::RecoCo static int tfID = 0; const auto& v0id = v0IDs[iv]; - if (mRefit && !refitV0(v0id, v0ext.v0, recoData)) { - invalidate(); - return v0ext; + if (mRefit) { + const auto* v0refit = getV0(iv, recoData); + if (!v0refit) { + invalidate(); + return v0ext; + } + v0ext.v0 = *v0refit; } const auto& v0sel = mRefit ? v0ext.v0 : v0s[iv]; if (mMaxEta < std::abs(v0sel.getEta())) { @@ -232,7 +361,7 @@ o2::dataformats::V0Ext SVStudySpec::processV0(int iv, o2::globaltracking::RecoCo v0ext.v0ID = v0id; const auto clRefs = recoData.getTPCTracksClusterRefs(); o2::MCCompLabel lb[2]; - const o2::MCTrack* mcTrks[2]; + const o2::MCTrack* mcTrks[2] = {nullptr, nullptr}; for (int ip = 0; ip < 2; ip++) { auto& prInfo = v0ext.prInfo[ip]; auto gid = v0ext.v0ID.getProngID(ip); @@ -301,15 +430,16 @@ o2::dataformats::V0Ext SVStudySpec::processV0(int iv, o2::globaltracking::RecoCo } } } - if (mUseMC && lb[ip].isValid()) { // temp store of mctrks - mcTrks[ip] = mcReader->getTrack(lb[ip]); + if (mcReader && lb[ip].isValid()) { // temp store of mctrks + mMCEventsTF.emplace(lb[ip].getSourceID(), lb[ip].getEventID()); + mcTrks[ip] = getMCTrack(lb[ip].getSourceID(), lb[ip].getEventID(), lb[ip].getTrackID()); } } - if (mUseMC && (mcTrks[0] != nullptr) && (mcTrks[1] != nullptr)) { + if (mcReader && (mcTrks[0] != nullptr) && (mcTrks[1] != nullptr)) { // check majority vote on mother particle otherwise leave pdg -1 if (lb[0].getSourceID() == lb[1].getSourceID() && lb[0].getEventID() == lb[1].getEventID() && mcTrks[0]->getMotherTrackId() == mcTrks[1]->getMotherTrackId() && mcTrks[0]->getMotherTrackId() >= 0) { - const auto mother = mcReader->getTrack(lb[0].getSourceID(), lb[0].getEventID(), mcTrks[0]->getMotherTrackId()); + const auto mother = getMCTrack(lb[0].getSourceID(), lb[0].getEventID(), mcTrks[0]->getMotherTrackId()); v0ext.mcPID = mother->GetPdgCode(); } } @@ -320,9 +450,6 @@ void SVStudySpec::process(o2::globaltracking::RecoContainer& recoData) { auto v0IDs = recoData.getV0sIdx(); auto nv0 = v0IDs.size(); - if (nv0 > recoData.getV0s().size()) { - mRefit = true; - } std::map> pv2sv; static int tfID = 0; for (int iv = 0; iv < nv0; iv++) { @@ -347,9 +474,7 @@ void SVStudySpec::process(o2::globaltracking::RecoContainer& recoData) if (v0extVec.size()) { const auto& pv = recoData.getPrimaryVertex(pvID); float tpcOccBef = 0., tpcOccAft = 0.; - int tb = pv.getTimeStamp().getTimeStamp() * mTPCTBinMUSInv * mNTPCOccBinLengthInv; - tpcOccBef = tb < 0 ? mTBinClOccBef[0] : (tb >= mTBinClOccBef.size() ? mTBinClOccBef.back() : mTBinClOccBef[tb]); - tpcOccAft = tb < 0 ? mTBinClOccAft[0] : (tb >= mTBinClOccAft.size() ? mTBinClOccAft.back() : mTBinClOccAft[tb]); + getTPCOccupancy(pv, tpcOccBef, tpcOccAft); (*mDBGOut) << "v0" << "orbit=" << recoData.startIR.orbit << "tfID=" << tfID << "tpcOccBef=" << tpcOccBef << "tpcOccAft=" << tpcOccAft @@ -363,8 +488,8 @@ void SVStudySpec::process(o2::globaltracking::RecoContainer& recoData) bool SVStudySpec::refitV0(const V0ID& id, o2::dataformats::V0& v0, o2::globaltracking::RecoContainer& recoData) { - auto seedP = recoData.getTrackParam(id.getProngID(0)); - auto seedN = recoData.getTrackParam(id.getProngID(1)); + auto seedP = getProngSeed(id.getProngID(0), id.getVertexID(), recoData); + auto seedN = getProngSeed(id.getProngID(1), id.getVertexID(), recoData); bool isTPConly = (id.getProngID(0).getSource() == GTrackID::TPC) || (id.getProngID(1).getSource() == GTrackID::TPC); const auto& svparam = o2::vertexing::SVertexerParams::Instance(); if (svparam.mTPCTrackPhotonTune && isTPConly) { @@ -405,9 +530,750 @@ bool SVStudySpec::refitV0(const V0ID& id, o2::dataformats::V0& v0, o2::globaltra return true; } +o2::track::TrackParCov SVStudySpec::getProngSeed(GTrackID gid, int vtxID, const o2::globaltracking::RecoContainer& recoData) const +{ + // prong track as the V0 finder fits it (SVertexer::processTPCTrack, correctTPCTrack): a TPC-only track with clusters on one side + // only is shifted in z from its time0 to the time of the vertex of the V0, its z error enlarged by the vertex time error; one with + // clusters on both sides keeps its z, the error enlarged by half its time window. Equal to the finder's V0s for its default settings + // and the same svertexer.* parameters: the V0 copies the finder adds for cascades at another vertex keep the fit of the original V0, + // here they are refitted at their own vertex (differs only with svertexer.mSkipTPCOnlyCascade=false and a TPC-only prong) + auto seed = recoData.getTrackParam(gid); + if (gid.getSource() != GTrackID::TPC) { + return seed; + } + const auto& trTPC = recoData.getTPCTrack(gid); + const float mus2TB = 1.f / (8 * o2::constants::lhc::LHCBunchSpacingMUS); + float tTB = trTPC.getTime0(); + float tTBErr = 0.5f * (trTPC.getDeltaTBwd() + trTPC.getDeltaTFwd()); + if (!trTPC.hasBothSidesClusters()) { + const auto& ts = recoData.getPrimaryVertex(vtxID).getTimeStamp(); + tTB = ts.getTimeStamp() * mus2TB; + tTBErr = ts.getTimeStampError() * mus2TB; + } + const float dDrift = (tTB - trTPC.getTime0()) * mTPCBin2Z; + const float driftErr = tTBErr * mTPCBin2Z; + seed.setZ(trTPC.getZ() + (trTPC.hasASideClustersOnly() ? dDrift : -dDrift)); + seed.setCov(seed.getSigmaZ2() + driftErr * driftErr, o2::track::kSigZ2); + return seed; +} + +const o2::dataformats::V0* SVStudySpec::getV0(int iv, o2::globaltracking::RecoContainer& recoData) +{ + // the V0 of the finder if it sent them (svertexer.createFullV0s), else the refit of this device, done once per TF + if (!mRefit) { + return &recoData.getV0s()[iv]; + } + if (mRefitStatus[iv] < 0) { + mRefitStatus[iv] = refitV0(recoData.getV0sIdx()[iv], mRefitV0s[iv], recoData) ? 1 : 0; + } + return mRefitStatus[iv] ? &mRefitV0s[iv] : nullptr; +} + +void SVStudySpec::getTPCOccupancy(const PVertex& pv, float& occBef, float& occAft) const +{ + // TPC clusters before / after the time of the primary vertex (0 without the TPC occupancy map) + occBef = occAft = 0.f; + if (mTBinClOccBef.empty() || mTBinClOccAft.empty()) { + return; + } + int tb = pv.getTimeStamp().getTimeStamp() * mTPCTBinMUSInv * mNTPCOccBinLengthInv; + occBef = tb < 0 ? mTBinClOccBef[0] : (tb >= mTBinClOccBef.size() ? mTBinClOccBef.back() : mTBinClOccBef[tb]); + occAft = tb < 0 ? mTBinClOccAft[0] : (tb >= mTBinClOccAft.size() ? mTBinClOccAft.back() : mTBinClOccAft[tb]); +} + +bool SVStudySpec::passProngCuts(const V0ID& id, const o2::globaltracking::RecoContainer& recoData) const +{ + // cuts that need only the prong tracks: applied before the refit + const auto& par = V0FullOutputParams::Instance(); + int charge[2] = {0, 0}; + for (int ip = 0; ip < 2; ip++) { + const auto gid = id.getProngID(ip); + charge[ip] = recoData.getTrackParam(gid).getCharge(); + const auto refs = recoData.getSingleDetectorRefs(gid); + const bool hasTPC = refs[GTrackID::TPC].isIndexSet(); + if (par.requireTPCBoth && !hasTPC) { + return false; + } + if (hasTPC && recoData.getTPCTrack(refs[GTrackID::TPC]).getNClusters() < par.minTPCClusters) { + return false; + } + } + return !par.requireOppositeCharges || charge[0] * charge[1] < 0; +} + +bool SVStudySpec::passFarLegCuts(const V0ID& id, const o2::globaltracking::RecoContainer& recoData) const +{ + // far V0s: both legs with at least minTPCClustersFar TPC clusters + const auto& par = V0FullOutputParams::Instance(); + for (int ip = 0; ip < 2; ip++) { + const auto refs = recoData.getSingleDetectorRefs(id.getProngID(ip)); + if (!refs[GTrackID::TPC].isIndexSet() || recoData.getTPCTrack(refs[GTrackID::TPC]).getNClusters() < par.minTPCClustersFar) { + return false; + } + } + return true; +} + +namespace +{ +/// MC truth of a particle: PDG code, momentum and point at its production +void fillMCTruth(const o2::MCTrack& trk, int& pdg, float (&p)[3], float (&vtx)[3]) +{ + pdg = trk.GetPdgCode(); + p[0] = trk.Px(); + p[1] = trk.Py(); + p[2] = trk.Pz(); + vtx[0] = trk.Vx(); + vtx[1] = trk.Vy(); + vtx[2] = trk.Vz(); +} + +} // namespace + +int SVStudySpec::addProng(GTrackID gid, const o2::globaltracking::RecoContainer& recoData, FullOutput& out) +{ + // each track is built once per TF (the V0s sharing it get copies of the same entry at the end of the TF) + const auto found = out.prongEntry.find(gid.getRawWOFlags()); + if (found != out.prongEntry.end()) { + return found->second; + } + const int entry = out.prongs.size(); + out.prongEntry[gid.getRawWOFlags()] = entry; + auto& prong = out.prongs.emplace_back(); + prong.gid = gid; + prong.track = recoData.getTrackParam(gid); + float t = 0.f; + float tErr = 0.f; + recoData.getTrackTime(gid, t, tErr); + if (gid.getSource() == GTrackID::TPC) { // TPC-only tracks give their time in time bins + t *= mTPCTBinMUS; + tErr *= mTPCTBinMUS; + } + prong.timeMUS = t; + prong.timeErrMUS = tErr; + if (mUseMC) { + prong.mcLabel = recoData.getTrackMCLabel(gid); + if (mcReader && prong.mcLabel.isValid()) { + mMCEventsTF.emplace(prong.mcLabel.getSourceID(), prong.mcLabel.getEventID()); + if (const auto* mcTrk = getMCTrack(prong.mcLabel.getSourceID(), prong.mcLabel.getEventID(), prong.mcLabel.getTrackID())) { + fillMCTruth(*mcTrk, prong.mcPDG, prong.mcP, prong.mcVtx); + } + } + } + const auto refs = recoData.getSingleDetectorRefs(gid); + if (refs[GTrackID::ITSTPC].isIndexSet()) { + prong.chi2ITSTPC = recoData.getTPCITSTrack(refs[GTrackID::ITSTPC]).getChi2Match(); + } + // TPC: the attached clusters, in the order of the track's cluster references + if (refs[GTrackID::TPC].isIndexSet()) { + const auto& trk = recoData.getTPCTrack(refs[GTrackID::TPC]); + prong.tpc = trk; + prong.flags |= o2::dataformats::V0Prong::HasTPC; + const auto& clusters = recoData.getTPCClusters(); + const auto clRefs = recoData.getTPCTracksClusterRefs(); + prong.clTPC.reserve(trk.getNClusterReferences()); + for (int j = 0; j < trk.getNClusterReferences(); j++) { + uint8_t sector = 0; + uint8_t row = 0; + uint32_t clIdx = 0; + trk.getClusterReference(clRefs, j, sector, row, clIdx); + auto& cl = prong.clTPC.emplace_back(); + cl.cl = clusters.clusters[sector][row][clIdx]; + cl.sector = sector; + cl.row = row; + if (!recoData.clusterShMapTPC.empty()) { + cl.shMap = recoData.clusterShMapTPC[clusters.clusterOffset[sector][row] + clIdx]; + } + } + } + // ITS: clusters of the ITS track, or of the afterburner tracklet attached in the ITS-TPC matching + std::vector itsIndices; + if (refs[GTrackID::ITS].isIndexSet()) { + const auto& trk = recoData.getITSTrack(refs[GTrackID::ITS]); + const auto clRefs = recoData.getITSTracksClusterRefs(); + for (int i = 0; i < trk.getNumberOfClusters(); i++) { + itsIndices.push_back(clRefs[trk.getFirstClusterEntry() + i]); + } + prong.flags |= o2::dataformats::V0Prong::HasITS; + } else if (refs[GTrackID::ITSAB].isIndexSet()) { + const auto& ab = recoData.getITSABRef(refs[GTrackID::ITSAB]); + const auto clRefs = recoData.getITSABClusterRefs(); + for (int i = 0; i < ab.getEntries(); i++) { + itsIndices.push_back(clRefs[ab.getFirstEntry() + i]); + } + prong.flags |= o2::dataformats::V0Prong::HasITS | o2::dataformats::V0Prong::ITSAB; + } + const auto itsClusters = recoData.getITSClusters(); + const auto rofs = recoData.getITSClustersROFRecords(); + for (const int idx : itsIndices) { + if (idx < 0 || idx >= (int)itsClusters.size()) { + continue; + } + const auto& c = itsClusters[idx]; + auto& cl = prong.clITS.emplace_back(); + cl.chipID = c.getSensorID(); + cl.row = c.getRow(); + cl.col = c.getCol(); + cl.pattID = c.getPatternID(); + if (c.getPatternID() == o2::itsmft::CompCluster::InvalidPatternID || (mITSDict && mITSDict->isGroup(c.getPatternID()))) { + out.pattRequests.push_back({entry, int(prong.clITS.size()) - 1, idx}); // pattern bytes in the TF's pattern stream, copied by fillITSPatterns + } + auto rof = std::upper_bound(rofs.begin(), rofs.end(), idx, [](int v, const o2::itsmft::ROFRecord& r) { return v < r.getFirstEntry(); }); + if (rof != rofs.begin()) { + cl.rofBC = std::prev(rof)->getBCData().differenceInBC(mTFStart); + } + } + // TOF: the matched cluster + if (refs[GTrackID::TOF].isIndexSet()) { + const auto tofClusters = recoData.getTOFClusters(); + const int idx = refs[GTrackID::TOF].getIndex(); + if (idx < (int)tofClusters.size()) { + const auto& c = tofClusters[idx]; + auto& cl = prong.clTOF.emplace_back(); + cl.timeRaw = c.getTimeRaw(); + cl.tot = c.getTot(); + cl.channel = c.getMainContributingChannel(); + prong.flags |= o2::dataformats::V0Prong::HasTOF; + const auto& match = recoData.getTOFMatch(gid); + prong.tofSignal = match.getSignal(); + prong.tofLength = match.getLTIntegralOut().getL(); + for (int ipid = 0; ipid < 5; ipid++) { + prong.tofExpTime[ipid] = match.getLTIntegralOut().getTOF(ipid); + } + } + } + // TRD: the tracklets of the TPC-TRD or ITS-TPC-TRD track + if (refs[GTrackID::TRD].isIndexSet()) { + const auto& trk = recoData.getTrack(refs[GTrackID::TRD]); + const auto tracklets = recoData.getTRDTracklets(); + const auto trigs = recoData.getTRDTriggerRecords(); + for (int layer = 0; layer < 6; layer++) { + const int it = trk.getTrackletIndex(layer); + if (it < 0 || it >= (int)tracklets.size()) { + continue; + } + auto& tr = prong.trdTracklets.emplace_back(); + tr.word = tracklets[it].getTrackletWord(); + tr.layer = layer; + auto trig = std::upper_bound(trigs.begin(), trigs.end(), it, [](int v, const o2::trd::TriggerRecord& t) { return v < t.getFirstTracklet(); }); + if (trig != trigs.begin()) { + tr.trigBC = std::prev(trig)->getBCData().differenceInBC(mTFStart); + } + } + prong.flags |= o2::dataformats::V0Prong::HasTRD; + } + return entry; +} + +const o2::MCTrack* SVStudySpec::getMCTrack(int source, int event, int track) const +{ + // MC particle, or nullptr: the reader throws for a source / event beyond its kinematics (e.g. a collision context of another TF) + if (!mcReader) { + return nullptr; + } + try { + return mcReader->getTrack(source, event, track); + } catch (const std::exception& e) { + if (!mMCWarned) { + LOGP(warning, "MC: no MC particle for label (source {}, event {}, track {}): {}; MC truth of such labels not stored (warned once)", source, event, track, e.what()); + mMCWarned = true; + } + return nullptr; + } +} + +void SVStudySpec::setV0Truth(o2::dataformats::TrackV0Extended& v0, const o2::dataformats::V0Prong& pos, const o2::dataformats::V0Prong& neg) const +{ + // MC truth of the V0: the common mother of its prongs, if they are two different MC particles of the same source and event with the same + // mother, each from a decay or pair production (in the transport or a decay of the generator; not e.g. a hadronic interaction in + // material), both produced at one point >= 1 um away from the production point of the mother (a displaced decay / conversion), and the + // mother is not a beam particle (HepMC status 4: generator primaries are attached to the beams). Short-lived particles decayed by the + // generator can pass the displacement (e.g. pi0 Dalitz pairs at high pT): use mcPDG + const auto& lbP = pos.mcLabel; + const auto& lbN = neg.mcLabel; + if (!mcReader || !lbP.isValid() || !lbN.isValid() || lbP.getSourceID() != lbN.getSourceID() || lbP.getEventID() != lbN.getEventID() || + lbP.getTrackID() == lbN.getTrackID()) { + return; + } + const int src = lbP.getSourceID(); + const int ev = lbP.getEventID(); + const auto* trkP = getMCTrack(src, ev, lbP.getTrackID()); + const auto* trkN = getMCTrack(src, ev, lbN.getTrackID()); + if (!trkP || !trkN || trkP->getMotherTrackId() < 0 || trkP->getMotherTrackId() != trkN->getMotherTrackId()) { + return; + } + auto fromDecay = [](const o2::MCTrack& trk) { + return trk.isPrimary() || trk.getProcess() == TMCProcess::kPDecay || trk.getProcess() == TMCProcess::kPPair; + }; + if (!fromDecay(*trkP) || !fromDecay(*trkN)) { + return; + } + const int motherID = trkP->getMotherTrackId(); + const auto* mother = getMCTrack(src, ev, motherID); + if (!mother || (mother->isPrimary() && o2::mcgenstatus::getHepMCStatusCode(mother->getStatusCode()) == 4)) { // none, or a beam particle + return; + } + const float minDist2 = 1e-4f * 1e-4f; // (1 um)^2 [cm^2] + auto dist2 = [](const o2::MCTrack& a, const o2::MCTrack& b) { + return float((a.Vx() - b.Vx()) * (a.Vx() - b.Vx()) + (a.Vy() - b.Vy()) * (a.Vy() - b.Vy()) + (a.Vz() - b.Vz()) * (a.Vz() - b.Vz())); + }; + if (dist2(*trkP, *trkN) > minDist2 || dist2(*trkP, *mother) < minDist2) { // not one displaced decay point + return; + } + v0.mcLabel = o2::MCCompLabel(motherID, ev, src); + fillMCTruth(*mother, v0.mcPDG, v0.mcP, v0.mcVtx); + v0.mcPrimary = mother->isPrimary(); + if (mother->getMotherTrackId() >= 0) { + if (const auto* grandMother = getMCTrack(src, ev, mother->getMotherTrackId())) { + v0.mcMotherPDG = grandMother->GetPdgCode(); + } + } +} + +void SVStudySpec::fillITSPatterns(const o2::globaltracking::RecoContainer& recoData, FullOutput& out) const +{ + // the TF's pattern stream holds, in cluster order, the patterns of the clusters with an invalid or a group pattern ID + if (!mITSDict) { + if (!mNoDictWarned) { + LOGP(warning, "No ITS cluster dictionary: patterns of ITS clusters of V0 prongs are not stored"); + mNoDictWarned = true; + } + return; + } + auto& requests = out.pattRequests; + std::sort(requests.begin(), requests.end(), [](const ITSPattRequest& a, const ITSPattRequest& b) { return a.index < b.index; }); + const auto clusters = recoData.getITSClusters(); + auto pattIt = recoData.getITSClustersPatterns().begin(); + size_t ir = 0; + for (int k = 0; k < (int)clusters.size() && ir < requests.size(); k++) { + const auto pattID = clusters[k].getPatternID(); + if (pattID != o2::itsmft::CompCluster::InvalidPatternID && !mITSDict->isGroup(pattID)) { + continue; + } + const auto start = pattIt; + o2::itsmft::ClusterPattern::skipPattern(pattIt); + for (; ir < requests.size() && requests[ir].index == k; ir++) { + auto& prong = out.prongs[requests[ir].prong]; + prong.clITS[requests[ir].cluster].pattEntry = prong.itsPatterns.size(); + prong.itsPatterns.insert(prong.itsPatterns.end(), start, pattIt); + } + } +} + +namespace +{ +/// reproducible pseudo-random number in [0, 1) of a V0 of a TF: splitmix64 of the TF counter and the V0's prong pair (the global track IDs of +/// its two prongs), independent of the order of the V0 finder's output (which depends on its threads) +double v0Random(uint32_t tfCounter, uint64_t prongPair) +{ + uint64_t z = (prongPair ^ (uint64_t(tfCounter) * 0xd1b54a32d192ed03ULL)) + 0x9e3779b97f4a7c15ULL; + z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL; + z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL; + z = z ^ (z >> 31); + return (z >> 11) * (1. / 9007199254740992.); +} +} // namespace + +int SVStudySpec::countCompatiblePVs(const V0ID& id, const o2::globaltracking::RecoContainer& recoData) const +{ + // primary vertices whose time is compatible with both prongs: a TPC-only prong (on one side) by its TPC time window, else by its time + const auto& par = V0FullOutputParams::Instance(); + float tMin = -1e9f; + float tMax = 1e9f; + for (int ip = 0; ip < 2; ip++) { + const auto gid = id.getProngID(ip); + float lo = 0.f; + float hi = 0.f; + if (gid.getSource() == GTrackID::TPC) { + const auto& trk = recoData.getTPCTrack(gid); + lo = (trk.getTime0() - trk.getDeltaTBwd()) * mTPCTBinMUS; + hi = (trk.getTime0() + trk.getDeltaTFwd()) * mTPCTBinMUS; + } else { + float t = 0.f; + float tErr = 0.f; + recoData.getTrackTime(gid, t, tErr); + lo = t - par.pvTimeNSigma * tErr; + hi = t + par.pvTimeNSigma * tErr; + } + tMin = std::max(tMin, lo); + tMax = std::min(tMax, hi); + } + int n = 0; + for (const auto& pv : recoData.getPrimaryVertices()) { + const float t = pv.getTimeStamp().getTimeStamp(); + const float err = par.pvTimeNSigma * pv.getTimeStamp().getTimeStampError(); + n += (t + err >= tMin && t - err <= tMax); + } + return n; +} + +void SVStudySpec::processFull(o2::globaltracking::RecoContainer& recoData, ProcessingContext& pc) +{ + const auto& par = V0FullOutputParams::Instance(); + o2::dataformats::TFIDInfo tfID; + o2::base::TFIDInfoHelper::fillTFIDInfo(pc, tfID); + mTFStart = {0, tfID.firstTForbit}; + o2::dataformats::V0sTFInfo tfInfo; + tfInfo.vDrift = mCorrMap->getVDrift(); + tfInfo.t0 = mCorrMap->getT0(); + tfInfo.lumi = mCorrMap->getLumi(); + tfInfo.idc = mCorrMap->getIDC(); + + using V0C = o2::dataformats::TrackV0Extended; + FullOutput out; + const auto v0IDs = recoData.getV0sIdx(); + const float massK0 = o2::constants::physics::MassK0Short; + const float massLambda = o2::constants::physics::MassLambda; + // 1) selected candidates (no clusters yet), with their sampling class and pT bin + struct Sel { + int iv; + int bin; + double rnd; + V0C cand; + }; + std::vector sel; + const double logPtMin = std::log10(par.ptMin); + const double logPtMax = std::log10(par.ptMax); + // 0) the V0 finder builds a pair with TPC-only prongs once per compatible primary vertex (track shifted in z to the vertex time): + // per prong pair only the copy with the largest cosPA is kept; the number of copies and the second-best one are stored + struct PairCopies { + int best = -1; + int second = -1; + int n = 0; + }; + std::unordered_map pairs; + std::vector pairKey(v0IDs.size(), 0); + size_t nCopies = 0; + for (int iv = 0; iv < (int)v0IDs.size(); iv++) { + const auto& id = v0IDs[iv]; + if (id.getVertexID() < 0 || !passProngCuts(id, recoData)) { + continue; + } + const auto* v0 = getV0(iv, recoData); + if (!v0) { + continue; + } + pairKey[iv] = (uint64_t(id.getProngID(0).getRawWOFlags()) << 32) | id.getProngID(1).getRawWOFlags(); + auto& cp = pairs[pairKey[iv]]; // key != 0: the two prongs are different tracks + cp.n++; + nCopies++; + const float cosPA = v0->getCosPA(); + if (cp.best < 0 || cosPA > getV0(cp.best, recoData)->getCosPA()) { + cp.second = cp.best; + cp.best = iv; + } else if (cp.second < 0 || cosPA > getV0(cp.second, recoData)->getCosPA()) { + cp.second = iv; + } + } + // DCA of each leg to the primary vertex: the V0's prong (at the decay vertex, in the frame of this vertex copy) propagated back to it; + // a failed propagation (low-pT leg whose helix cannot reach the vertex) leaves -999 + auto fillLegDCA = [](const o2::dataformats::V0& v0, const PVertex& pv, V0C& cand) { + for (int ip = 0; ip < 2; ip++) { + auto leg = v0.getProng(ip); + o2::dataformats::DCA dcaLeg; + if (o2::base::Propagator::Instance()->propagateToDCABxByBz(pv, leg, 2.f, o2::base::Propagator::MatCorrType::USEMatCorrLUT, &dcaLeg)) { + cand.legDCAxy[ip] = dcaLeg.getY(); + cand.legDCAz[ip] = dcaLeg.getZ(); + } + } + }; + for (int iv = 0; iv < (int)v0IDs.size(); iv++) { + const auto& id = v0IDs[iv]; + if (!pairKey[iv]) { // no vertex, failed the prong cuts or the refit + continue; + } + const auto& copies = pairs[pairKey[iv]]; + if (copies.best != iv) { + continue; + } + const auto* v0 = getV0(iv, recoData); + V0C cand; + cand.nPairPV = copies.n; + if (copies.second >= 0) { + cand.cosPA2 = getV0(copies.second, recoData)->getCosPA(); + } + cand.dca = v0->getDCA(); + cand.cosPA = v0->getCosPA(); + cand.qT = v0->calcAPQt(); + cand.alpha = v0->calcAPAlpha(); + cand.r = std::sqrt(v0->calcR2()); + cand.massK0 = std::sqrt(std::max(0.f, v0->calcMass2AsK0())); + cand.massLambda = std::sqrt(std::max(0.f, v0->calcMass2AsLambda())); + cand.massAntiLambda = std::sqrt(std::max(0.f, v0->calcMass2AsAntiLambda())); + cand.massGamma = std::sqrt(std::max(0.f, v0->calcMass2AsPhoton())); + // far V0s (beyond maxR, both legs without ITS) get their own cuts + const bool far = par.selFar && cand.r > par.maxR && !id.getProngID(0).includesDet(DetID::ITS) && !id.getProngID(1).includesDet(DetID::ITS); + const float maxDCA = far ? par.maxDCAFar : par.maxDCA; + const float minCosPA = far ? par.minCosPAFar : par.minCosPA; + const float maxR = far ? par.maxRFar : par.maxR; + const float dmK0 = far ? par.maxDMassK0Far : par.maxDMassK0; + const float dmL = far ? par.maxDMassLambdaFar : par.maxDMassLambda; + const float minQt = far ? par.minQtFar : par.minQt; + if (!(cand.dca > maxDCA || cand.cosPA < minCosPA || cand.qT < minQt || cand.qT > par.maxQt || cand.r < par.minR || cand.r > maxR || (far && !passFarLegCuts(id, recoData)))) { + // far V0s: proper decay length from the assigned primary vertex (no cut on the others) + float ctOverM = 0.f; + if (far) { + const auto& pv = recoData.getPrimaryVertex(id.getVertexID()); + std::array xyz; + v0->getXYZGlo(xyz); + const float dx = xyz[0] - pv.getX(); + const float dy = xyz[1] - pv.getY(); + const float dz = xyz[2] - pv.getZ(); + ctOverM = std::sqrt(dx * dx + dy * dy + dz * dz) / std::max(1e-6f, v0->getP()); + } + const bool lambdaLike = std::min(std::abs(cand.massLambda - massLambda), std::abs(cand.massAntiLambda - massLambda)) < par.vetoDMassLambdaK0; + const bool k0FarOK = cand.qT > par.minQtK0Far && ctOverM * massK0 < par.maxCtK0Far; + if (par.selK0 && std::abs(cand.massK0 - massK0) < dmK0 && (far ? k0FarOK : !lambdaLike)) { + cand.selection |= V0C::K0; + } + // Lambdas within maxR: K0s reflection vetoed (far ones: their alpha window stays below the crossing of the two ellipses) + const bool lambdaOK = far ? ctOverM * massLambda < par.maxCtLambdaFar : std::abs(cand.massK0 - massK0) >= par.vetoDMassK0Lambda; + const float maxAlphaL = far ? par.maxAlphaLambdaFar : par.maxAlphaLambda; + if (par.selLambda && lambdaOK && cand.alpha > par.minAlphaLambda && cand.alpha < maxAlphaL && std::abs(cand.massLambda - massLambda) < dmL) { + cand.selection |= V0C::Lambda; + } + if (par.selLambda && lambdaOK && cand.alpha < -par.minAlphaLambda && cand.alpha > -maxAlphaL && std::abs(cand.massAntiLambda - massLambda) < dmL) { + cand.selection |= V0C::AntiLambda; + } + if (far && cand.selection) { + cand.selection |= V0C::Far; + } + } + const float apGamma = (cand.alpha / par.maxAlphaGamma) * (cand.alpha / par.maxAlphaGamma) + (cand.qT / par.maxQtGamma) * (cand.qT / par.maxQtGamma); + // photon legs displaced from the vertex (computed only for candidates passing the other photon cuts; the result is kept for the output) + auto legsDisplaced = [&]() { + if (par.minLegDCAXYGamma < 0.f) { + return true; + } + fillLegDCA(*v0, recoData.getPrimaryVertex(id.getVertexID()), cand); + for (int ip = 0; ip < 2; ip++) { + if (cand.legDCAxy[ip] > -998.f && std::abs(cand.legDCAxy[ip]) < par.minLegDCAXYGamma) { + return false; + } + } + return true; + }; + if (par.selGamma && (id.isPhotonOnly() || cand.massGamma < par.maxMassGamma) && apGamma < 1.f && cand.r > par.minRGamma && cand.r < par.maxRGamma && + cand.cosPA > par.minCosPAGamma && (par.maxDCAGamma < 0.f || cand.dca < par.maxDCAGamma) && legsDisplaced()) { + cand.selection |= V0C::Gamma; + } + if (!cand.selection) { + continue; + } + cand.sampleClass = (cand.selection & V0C::K0) ? V0C::ClassK0 : ((cand.selection & V0C::Lambda) ? V0C::ClassLambda : ((cand.selection & V0C::AntiLambda) ? V0C::ClassAntiLambda : V0C::ClassGamma)); + if (id.isPhotonOnly()) { + cand.selection |= V0C::PhotonOnly; + } + cand.v0 = *v0; + const double logPt = std::log10(std::max(1e-6f, v0->getPt())); + const int bin = logPt < logPtMin ? 0 : (logPt >= logPtMax ? par.nPtBins + 1 : 1 + int((logPt - logPtMin) / (logPtMax - logPtMin) * par.nPtBins)); + sel.push_back({iv, bin, v0Random(tfID.tfCounter, pairKey[iv]), cand}); + } + // 1b) V0s sharing a track (before the downsampling, which may drop the competitors): count and greedy matching by legScore + { + // legScore = w * 60 * acos(cosPA) + (1 - w) * sqrt(dca) / 3 cm, w = legScoreWeight (lower: better), as the photon-conversion-builder + // deduplication in O2Physics + std::unordered_map> byLeg; + std::vector legScore(sel.size()); + for (int k = 0; k < (int)sel.size(); k++) { + const auto& c = sel[k].cand; + legScore[k] = par.legScoreWeight * 60.f * std::acos(std::clamp(c.cosPA, -1.f, 1.f)) + (1.f - par.legScoreWeight) * std::sqrt(std::max(0.f, c.dca)) / 3.f; + for (int ip = 0; ip < 2; ip++) { + byLeg[v0IDs[sel[k].iv].getProngID(ip).getRawWOFlags()].push_back(k); + } + } + std::vector order(sel.size()); + for (int k = 0; k < (int)sel.size(); k++) { + order[k] = k; + std::unordered_set others; + for (int ip = 0; ip < 2; ip++) { + for (int o : byLeg[v0IDs[sel[k].iv].getProngID(ip).getRawWOFlags()]) { + if (o != k) { + others.insert(o); + } + } + } + sel[k].cand.nSharedLeg = others.size(); + } + std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return legScore[a] < legScore[b]; }); + std::unordered_set usedLegs; + for (int k : order) { + const uint32_t l0 = v0IDs[sel[k].iv].getProngID(0).getRawWOFlags(); + const uint32_t l1 = v0IDs[sel[k].iv].getProngID(1).getRawWOFlags(); + if (!usedLegs.count(l0) && !usedLegs.count(l1)) { + sel[k].cand.selection |= V0C::BestForLegs; + usedLegs.insert(l0); + usedLegs.insert(l1); + } + } + } + // 2) flat in V0 pT, per class and bin with the cap maxPerBin* (V0s kept per TF and bin): cap >= 1: the int(cap) V0s with the lowest + // random numbers, weight = candidates / kept; 0 <= cap < 1: each V0 with probability cap / candidates, weight = candidates / cap. + // Far V0s (bit Far) are sampled separately from the other V0s of their class (group = class + 4), with maxPerBinFar: rare, they + // would otherwise be lost among the many V0s of the same class and pT bin + const float maxPerBin[4] = {par.maxPerBinK0, par.maxPerBinLambda, par.maxPerBinLambda, par.maxPerBinGamma}; + std::map, std::vector> groups; + for (int k = 0; k < (int)sel.size(); k++) { + groups[{sel[k].cand.sampleClass + ((sel[k].cand.selection & V0C::Far) ? 4 : 0), sel[k].bin}].push_back(k); + } + std::vector kept; + for (auto& [key, idx] : groups) { + const float cap = key.first >= 4 ? par.maxPerBinFar : maxPerBin[key.first]; + const int nCand = idx.size(); + if (cap >= 0.f && cap < 1.f) { + const float prob = cap / nCand; + for (int k : idx) { + if (sel[k].rnd < prob) { + sel[k].cand.weight = nCand / cap; + kept.push_back(k); + } + } + continue; + } + const int nKeep = cap < 0.f ? nCand : std::min(int(cap), nCand); + if (nKeep < nCand) { + std::sort(idx.begin(), idx.end(), [&](int a, int b) { return sel[a].rnd < sel[b].rnd; }); + } + for (int j = 0; j < nKeep; j++) { + sel[idx[j]].cand.weight = float(nCand) / nKeep; + kept.push_back(idx[j]); + } + } + std::sort(kept.begin(), kept.end()); // V0 finder order + // event time of a primary vertex from its TOF-matched tracks, for the TOF PID of the legs: per vertex (track, TOF signal - expected pion + // time) of its unambiguously associated tracks (filled when first needed); per V0 a robust mean without the V0's own legs + std::unordered_map>> pvTOFTimes; + const auto pvTracks = recoData.getPrimaryVertexMatchedTracks(); + const auto pvRefs = recoData.getPrimaryVertexMatchedTrackRefs(); + auto setEvTimeTOF = [&](V0C& cand, const V0ID& id) { + const int ipv = id.getVertexID(); + auto it = pvTOFTimes.find(ipv); + if (it == pvTOFTimes.end()) { + it = pvTOFTimes.emplace(ipv, std::vector>{}).first; + if (ipv >= 0 && ipv < (int)pvRefs.size()) { + const auto& ref = pvRefs[ipv]; + for (int src = 0; src < GTrackID::NSources; src++) { + if (!(GTrackID::getSourceDetectorsMask(src) & DetID::getMask(DetID::TOF)).any() || !recoData.isTrackSourceLoaded(src)) { + continue; // no TOF, or a source not in --track-sources (its matches are not loaded) + } + const int first = ref.getFirstEntryOfSource(src); + const int last = first + ref.getEntriesOfSource(src); + for (int i = first; i < last; i++) { + const auto& vid = pvTracks[i]; + if (vid.isAmbiguous()) { + continue; + } + const auto& match = recoData.getTOFMatch(vid); + it->second.emplace_back(vid.getRawWOFlags(), match.getSignal() - match.getLTIntegralOut().getTOF(o2::track::PID::Pion)); + } + } + } + } + const uint32_t leg0 = id.getProngID(0).getRawWOFlags(); + const uint32_t leg1 = id.getProngID(1).getRawWOFlags(); + std::vector t0s; + t0s.reserve(it->second.size()); + for (const auto& [raw, t0] : it->second) { + if (raw != leg0 && raw != leg1) { + t0s.push_back(t0); + } + } + if (t0s.empty()) { + return; + } + // start from the median (kaons and protons arrive late under the pion hypothesis), then twice the mean within +-300 ps (~3 sigma) + std::nth_element(t0s.begin(), t0s.begin() + t0s.size() / 2, t0s.end()); + double center = t0s[t0s.size() / 2]; + double sum = 0.; + double sum2 = 0.; + int n = 0; + for (int iter = 0; iter < 2; iter++) { + sum = 0.; + sum2 = 0.; + n = 0; + for (double t0 : t0s) { + if (std::abs(t0 - center) < 300.) { + sum += t0 - center; + sum2 += (t0 - center) * (t0 - center); + n++; + } + } + if (!n) { + return; + } + const double mean = sum / n; + sum2 = sum2 / n - mean * mean; + center += mean; + } + cand.evTimeTOF = center; + cand.evTimeTOFErr = std::sqrt(std::max(0., sum2) / n); + cand.evTimeTOFN = n; + }; + // 4) the kept V0s with their primary vertex, prongs and clusters + for (int k : kept) { + auto& cand = sel[k].cand; + const auto& id = v0IDs[sel[k].iv]; + const auto& pv = recoData.getPrimaryVertex(id.getVertexID()); + setEvTimeTOF(cand, id); + getTPCOccupancy(pv, cand.tpcOccBef, cand.tpcOccAft); + cand.pvX = pv.getX(); + cand.pvY = pv.getY(); + cand.pvZ = pv.getZ(); + cand.pvTimeMUS = pv.getTimeStamp().getTimeStamp(); + cand.pvTimeErrMUS = pv.getTimeStamp().getTimeStampError(); + cand.pvNContrib = pv.getNContributors(); + const auto& pvCov = pv.getCov(); + std::copy(pvCov.begin(), pvCov.end(), cand.pvCov); + if (cand.legDCAxy[0] < -998.f && cand.legDCAxy[1] < -998.f) { // not yet computed by the photon selection + fillLegDCA(cand.v0, pv, cand); + } + cand.nCompatPV = countCompatiblePVs(id, recoData); + out.v0Prongs.push_back({addProng(id.getProngID(0), recoData, out), addProng(id.getProngID(1), recoData, out)}); + if (mUseMC) { + setV0Truth(cand, out.prongs[out.v0Prongs.back()[0]], out.prongs[out.v0Prongs.back()[1]]); + } + out.v0s.push_back(cand); + } + if (!out.pattRequests.empty()) { + fillITSPatterns(recoData, out); + } + // 5) each V0 gets its own copy of its prongs with their clusters + size_t nClTPC = 0; + size_t nClITS = 0; + size_t nClTOF = 0; + size_t nTrkltTRD = 0; + for (size_t iv = 0; iv < out.v0s.size(); iv++) { + auto& v0 = out.v0s[iv]; + for (int ip = 0; ip < 2; ip++) { + auto& prong = v0.prong(ip); + prong = out.prongs[out.v0Prongs[iv][ip]]; + nClTPC += prong.clTPC.size(); + nClITS += prong.clITS.size(); + nClTOF += prong.clTOF.size(); + nTrkltTRD += prong.trdTracklets.size(); + } + } + mNV0sFull += out.v0s.size(); + mNProngsFull += out.prongs.size(); + mNClTPCFull += nClTPC; + int nPerClass[4] = {0, 0, 0, 0}; + for (const auto& v : out.v0s) { + nPerClass[v.sampleClass]++; + } + LOGP(info, "Full output of TF {}: {} V0s (K0s {}, Lambda {}, anti-Lambda {}, photons {}) of {} selected, {} candidates ({} after the prong cuts, {} prong pairs); {} distinct prong tracks; stored {} TPC, {} ITS, {} TOF clusters, {} TRD tracklets", + tfID.tfCounter, out.v0s.size(), nPerClass[0], nPerClass[1], nPerClass[2], nPerClass[3], sel.size(), v0IDs.size(), nCopies, pairs.size(), out.prongs.size(), nClTPC, nClITS, nClTOF, nTrkltTRD); + pc.outputs().snapshot(Output{"GLO", "V0FULL", 0}, out.v0s); + pc.outputs().snapshot(Output{"GLO", "V0FULLTF", 0}, tfInfo); + pc.outputs().snapshot(Output{"GLO", "V0FULLOCCMAP", 0}, std::vector(recoData.occupancyMapTPC.begin(), recoData.occupancyMapTPC.end())); + pc.outputs().snapshot(Output{"GLO", "V0FULLTFID", 0}, tfID); +} + void SVStudySpec::endOfStream(EndOfStreamContext& ec) { mDBGOut.reset(); + if (mFullOutput) { + LOGP(info, "SV study full output: {} V0s, {} distinct prong tracks, {} TPC clusters stored", mNV0sFull, mNProngsFull, mNClTPCFull); + } } void SVStudySpec::finaliseCCDB(ConcreteDataMatcher& matcher, void* obj) @@ -415,9 +1281,16 @@ void SVStudySpec::finaliseCCDB(ConcreteDataMatcher& matcher, void* obj) if (o2::base::GRPGeomHelper::instance().finaliseCCDB(matcher, obj)) { return; } + if (mTracksSrc[GTrackID::TPC] && mTPCVDriftHelper.accountCCDBInputs(matcher, obj)) { + return; + } + if (matcher == ConcreteDataMatcher("ITS", "CLUSDICT", 0)) { + mITSDict = (const o2::itsmft::TopologyDictionary*)obj; + return; + } } -DataProcessorSpec getSVStudySpec(GTrackID::mask_t srcTracks, GTrackID::mask_t srcCls, bool useMC) +DataProcessorSpec getSVStudySpec(GTrackID::mask_t srcTracks, GTrackID::mask_t srcCls, bool useMC, bool fullOutput) { std::vector outputs; auto dataRequest = std::make_shared(); @@ -427,6 +1300,16 @@ DataProcessorSpec getSVStudySpec(GTrackID::mask_t srcTracks, GTrackID::mask_t sr dataRequest->requestPrimaryVertices(useMC); dataRequest->requestSecondaryVertices(useMC); dataRequest->inputs.emplace_back("meanvtx", "GLO", "MEANVERTEX", 0, Lifetime::Condition, ccdbParamSpec("GLO/Calib/MeanVertex", {}, 1)); + if (srcTracks[GTrackID::TPC]) { + o2::tpc::VDriftHelper::requestCCDBInputs(dataRequest->inputs); + } + if (fullOutput) { + dataRequest->inputs.emplace_back("corrMap", o2::header::gDataOriginTPC, "TPCCORRMAP", 0, Lifetime::Timeframe); + outputs.emplace_back("GLO", "V0FULL", 0, Lifetime::Timeframe); + outputs.emplace_back("GLO", "V0FULLTF", 0, Lifetime::Timeframe); + outputs.emplace_back("GLO", "V0FULLOCCMAP", 0, Lifetime::Timeframe); + outputs.emplace_back("GLO", "V0FULLTFID", 0, Lifetime::Timeframe); + } auto ggRequest = std::make_shared(true, // orbitResetTime true, // GRPECS=true false, // GRPLHCIF @@ -440,11 +1323,12 @@ DataProcessorSpec getSVStudySpec(GTrackID::mask_t srcTracks, GTrackID::mask_t sr "sv-study", dataRequest->inputs, outputs, - AlgorithmSpec{adaptFromTask(dataRequest, ggRequest, srcTracks, useTPCcl, useMC)}, + AlgorithmSpec{adaptFromTask(dataRequest, ggRequest, srcTracks, useTPCcl, useMC, fullOutput)}, Options{ {"refit", VariantType::Bool, false, {"refit SVertices"}}, {"sel-k0", VariantType::Float, -1.f, {"If positive, select K0s with this mass margin"}}, {"max-eta", VariantType::Float, 1.2f, {"Cut on track eta"}}, + {"disable-study-tree", VariantType::Bool, false, {"do not write svStudy.root (e.g. with --full-output only)"}}, }}; } diff --git a/Detectors/GlobalTrackingWorkflow/study/src/V0FullOutputParams.cxx b/Detectors/GlobalTrackingWorkflow/study/src/V0FullOutputParams.cxx new file mode 100644 index 0000000000000..b6bce7459d461 --- /dev/null +++ b/Detectors/GlobalTrackingWorkflow/study/src/V0FullOutputParams.cxx @@ -0,0 +1,14 @@ +// Copyright 2019-2026 CERN and copyright holders of ALICE O2. +// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +// All rights not expressly granted are reserved. +// +// This software is distributed under the terms of the GNU General Public +// License v3 (GPL Version 3), copied verbatim in the file "COPYING". +// +// In applying this license CERN does 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 "GlobalTrackingStudy/V0FullOutputParams.h" + +O2ParamImpl(o2::svstudy::V0FullOutputParams); diff --git a/Detectors/GlobalTrackingWorkflow/study/src/V0FullWriterSpec.cxx b/Detectors/GlobalTrackingWorkflow/study/src/V0FullWriterSpec.cxx new file mode 100644 index 0000000000000..6d0d477114271 --- /dev/null +++ b/Detectors/GlobalTrackingWorkflow/study/src/V0FullWriterSpec.cxx @@ -0,0 +1,46 @@ +// Copyright 2019-2026 CERN and copyright holders of ALICE O2. +// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +// All rights not expressly granted are reserved. +// +// This software is distributed under the terms of the GNU General Public +// License v3 (GPL Version 3), copied verbatim in the file "COPYING". +// +// In applying this license CERN does 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 V0FullWriterSpec.cxx +/// @brief Writes the V0s with the raw clusters of their prongs (o2-sv-study-workflow --full-output) to o2_v0s_full.root, one entry per TF + +#include +#include +#include "GlobalTrackingStudy/SVStudy.h" +#include "DPLUtils/MakeRootTreeWriterSpec.h" +#include "DataFormatsGlobalTracking/TrackV0Extended.h" +#include "CommonDataFormat/TFIDInfo.h" + +using namespace o2::framework; + +namespace o2::svstudy +{ + +template +using BranchDefinition = MakeRootTreeWriterSpec::BranchDefinition; + +DataProcessorSpec getV0FullWriterSpec() +{ + auto logger = [](std::vector const& v0s) { + LOG(info) << "Writing " << v0s.size() << " V0s with clusters"; + }; + return MakeRootTreeWriterSpec("v0s-full-writer", + "o2_v0s_full.root", + "v0sFull", + -1, // do not limit number of events to store + 100, // periodically autosave + BranchDefinition>{InputSpec{"v0s", "GLO", "V0FULL", 0}, "v0s", 1, logger}, + BranchDefinition{InputSpec{"tfinfo", "GLO", "V0FULLTF", 0}, "tfInfo", 1}, + BranchDefinition>{InputSpec{"occmap", "GLO", "V0FULLOCCMAP", 0}, "tpcOccMap", 1}, + BranchDefinition{InputSpec{"tfid", "GLO", "V0FULLTFID", 0}, "tfID", 1})(); +} + +} // namespace o2::svstudy diff --git a/Detectors/GlobalTrackingWorkflow/study/src/sv-study-workflow.cxx b/Detectors/GlobalTrackingWorkflow/study/src/sv-study-workflow.cxx index 7e104b82f4854..116050d0f84d6 100644 --- a/Detectors/GlobalTrackingWorkflow/study/src/sv-study-workflow.cxx +++ b/Detectors/GlobalTrackingWorkflow/study/src/sv-study-workflow.cxx @@ -20,6 +20,9 @@ #include "DetectorsBase/DPLWorkflowUtils.h" #include "GlobalTrackingWorkflowHelpers/InputHelper.h" #include "DetectorsRaw/HBFUtilsInitializer.h" +#include "TPCWorkflow/TPCScalerSpec.h" +#include "TPCCalibration/CorrectionMapsOptions.h" +#include "DataFormatsITSMFT/DPLAlpideParamInitializer.h" using namespace o2::framework; using GID = o2::dataformats::GlobalTrackID; @@ -40,7 +43,11 @@ void customize(std::vector& workflowOptions) {"track-sources", VariantType::String, std::string{GID::ALL}, {"comma-separated list of track sources to use"}}, {"disable-root-input", VariantType::Bool, false, {"disable root-files input reader"}}, {"ignore-tpc-occ", VariantType::Bool, false, {"do not fill TPC occupancy (needs TPC clusters)"}}, + {"full-output", VariantType::Bool, false, {"also write the selected V0s (svFullOutput.* cuts) with the raw TPC / ITS / TOF clusters and TRD tracklets of their prongs to o2_v0s_full.root"}}, + {"disable-root-output", VariantType::Bool, false, {"with --full-output: send the V0s with clusters but do not add their writer"}}, {"configKeyValues", VariantType::String, "", {"Semicolon separated key=value strings ..."}}}; + o2::tpc::CorrectionMapsOptions::addGlobalOptions(options); + o2::itsmft::DPLAlpideParamInitializer::addITSConfigOption(options); o2::raw::HBFUtilsInitializer::addConfigOption(options); std::swap(workflowOptions, options); } @@ -63,13 +70,45 @@ WorkflowSpec defineDataProcessing(ConfigContext const& configcontext) GID::mask_t srcTrc = allowedSourcesTrc & GID::getSourcesMask(configcontext.options().get("track-sources")); GID::mask_t srcCls{}; bool fillTPCOcc = !configcontext.options().get("ignore-tpc-occ"); - if (fillTPCOcc) { + const bool fullOutput = configcontext.options().get("full-output"); + if (fillTPCOcc || fullOutput) { srcCls = srcCls | GID::getSourcesMask("TPC"); } - o2::globaltracking::InputHelper::addInputSpecs(configcontext, specs, srcCls, srcTrc, srcTrc, useMC); + GID::mask_t srcTrcIn = srcTrc; + if (fullOutput) { + // the prongs' ITS clusters are read through their ITS track (or ITS-AB tracklet of the ITS-TPC matching), also if standalone ITS + // tracks are not in --track-sources; the TPC map of the reconstruction comes from the TPC scaler device (in the reconstruction chain + // from the chain's one) + if (GID::includesDet(DetID::ITS, srcTrc)) { + srcTrcIn |= GID::getSourceMask(GID::ITS); + if (o2::itsmft::DPLAlpideParamInitializer::isITSStaggeringEnabled(configcontext)) { + LOG(warning) << "--full-output: staggered ITS clusters are not supported, the ITS clusters of the V0 prongs are not stored"; + } else { + srcCls |= GID::getSourceMask(GID::ITS); + } + } + // the matched TOF cluster and the TRD tracklets of the prongs + if (GID::includesDet(DetID::TOF, srcTrc)) { + srcCls |= GID::getSourceMask(GID::TOF); + } + if (GID::includesDet(DetID::TRD, srcTrc)) { + srcCls |= GID::getSourceMask(GID::TRD); + } + auto sclOpt = o2::tpc::CorrectionMapsOptions::parseGlobalOptions(configcontext.options()); + if (sclOpt.requestCTPLumi) { + srcTrcIn |= GID::getSourcesMask("CTP"); + } + if (!configcontext.options().get("disable-root-input")) { + specs.emplace_back(o2::tpc::getTPCScalerSpec(sclOpt)); + } + } + o2::globaltracking::InputHelper::addInputSpecs(configcontext, specs, srcCls, srcTrcIn, srcTrcIn, useMC); o2::globaltracking::InputHelper::addInputSpecsPVertex(configcontext, specs, useMC); // P-vertex is always needed o2::globaltracking::InputHelper::addInputSpecsSVertex(configcontext, specs); // S-vertex is always needed - specs.emplace_back(o2::svstudy::getSVStudySpec(srcTrc, srcCls, useMC)); + specs.emplace_back(o2::svstudy::getSVStudySpec(srcTrcIn, srcCls, useMC, fullOutput)); + if (fullOutput && !configcontext.options().get("disable-root-output")) { + specs.emplace_back(o2::svstudy::getV0FullWriterSpec()); + } // configure dpl timer to inject correct firstTForbit: start from the 1st orbit of TF containing 1st sampled orbit o2::raw::HBFUtilsInitializer hbfIni(configcontext, specs); diff --git a/prodtests/full-system-test/calib-workflow.sh b/prodtests/full-system-test/calib-workflow.sh index 8af9e2a24ea95..84b1b08960847 100644 --- a/prodtests/full-system-test/calib-workflow.sh +++ b/prodtests/full-system-test/calib-workflow.sh @@ -105,6 +105,14 @@ if [[ ${CALIB_ASYNC_EXTRACTCOSMICS:-0} == 1 ]] ; then fi add_W o2-cosmics-match-workflow "$DISABLE_ROOT_INPUT $DISABLE_MC --track-sources TPC --enable-cluster-output --road-detectors ${COSMICS_ROAD_DETECTORS:-none}$COSMICS_OPT" "$COSMICS_CONFIG" fi +if [[ ${CALIB_ASYNC_EXTRACTV0S:-0} == 1 ]] ; then + # V0s (K0s, Lambda, photon conversions) with the raw TPC / ITS / TOF clusters and TRD tracklets of their prongs -> o2_v0s_full.root + # (selection and downsampling: svFullOutput.*). It takes the V0 finder's V0s from the chain, without a refit if the finder sends the + # full V0s (svertexer.createFullV0s=true; the refit otherwise uses only this workflow's svertexer.* keys). With staggered ITS the + # prongs' ITS clusters are not stored + : ${V0S_TRACK_SOURCES:=$TRACK_SOURCES} + add_W o2-sv-study-workflow "$DISABLE_ROOT_INPUT $DISABLE_MC ${ITS_STAGGERED:-} --disable-study-tree --full-output --track-sources $V0S_TRACK_SOURCES $TPC_CORR_OPT" "$TPC_CORR_KEY" +fi # output-proxy for aggregator if workflow_has_parameter CALIB_PROXIES; then From 09fa48974a904401a83f6edab0f2bb31a8b711bd Mon Sep 17 00:00:00 2001 From: Matthias Kleiner Date: Fri, 4 Dec 2026 17:02:25 +0100 Subject: [PATCH 2/2] SVertexer: cosPA of the V0 clones for cascades from the global V0 position With svertexer.createFullV0s, the copy of a V0 that the finder adds for a cascade at another primary vertex got its cosPA from V0::getX()/getY(), i.e. from the coordinates in the V0's sector frame, combined with the global position of the vertex. The cosPA of these copies was wrong (e.g. -0.83 instead of 0.93). Use the global position of the V0 (getXYZGlo). Only the full V0 output (createFullV0s=true) is affected; the V0 indices, the fits and the AOD are unchanged. Test: Pb-Pb MC TF with the cascade finder: 2 of 1782 V0s are such copies; their cosPA changes from -0.83 / -0.23 to 0.93 / 0.99, nothing else changes. Co-Authored-By: Claude Opus 5.5 --- Detectors/Vertexing/src/SVertexer.cxx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Detectors/Vertexing/src/SVertexer.cxx b/Detectors/Vertexing/src/SVertexer.cxx index 2061eaeedf9d2..dcbbaf5a4b169 100644 --- a/Detectors/Vertexing/src/SVertexer.cxx +++ b/Detectors/Vertexing/src/SVertexer.cxx @@ -1034,7 +1034,12 @@ int SVertexer::checkCascades(const V0Index& v0Idx, const V0& v0, float rv0, std: mV0sIdxTmp[ithread].emplace_back(cascVtxID, v0Idx.getProngs()); if (mSVParams->createFullV0s) { mV0sTmp[ithread].push_back(v0); - float dx = v0.getX() - pv.getX(), dy = v0.getY() - pv.getY(), dz = v0.getZ() - pv.getZ(), prodXYZ = dx * pV0[0] + dy * pV0[1] + dz * pV0[2]; + // cosPA to the cascade's vertex: the V0 position in global coordinates (getX/getY are in the V0's sector frame) + const auto v0XYZ = v0.getXYZGlo(); + float dx = v0XYZ.X() - pv.getX(); + float dy = v0XYZ.Y() - pv.getY(); + float dz = v0XYZ.Z() - pv.getZ(); + float prodXYZ = dx * pV0[0] + dy * pV0[1] + dz * pV0[2]; mV0sTmp[ithread].back().setCosPA(prodXYZ / std::sqrt((dx * dx + dy * dy + dz * dz) * p2V0)); } }