diff --git a/Detectors/GenericTracking/base/include/GenericTracking/Base/LayerSpec.h b/Detectors/GenericTracking/base/include/GenericTracking/Base/LayerSpec.h index 91a146ac00099..3a788d756d4bf 100644 --- a/Detectors/GenericTracking/base/include/GenericTracking/Base/LayerSpec.h +++ b/Detectors/GenericTracking/base/include/GenericTracking/Base/LayerSpec.h @@ -221,9 +221,44 @@ struct Detector { } }(); + /// A crossing without a hit on an inactive layer consumes zero holes in + /// both the pair test (LinkHoles.h) and the follower (Follow.h). + /// Hits can enter the fit through seeding or following, including between + /// two rows of a road and after the + /// outward walk. Inactive layers leave the other layers' material slab + /// boundaries in place (LayerMaterial.h). One bit per layer, or zero when + /// the layout has no inactive layers. ALICE 3's iTOF and oTOF use this policy. + static constexpr std::uint64_t inactiveLayers = [] { + if constexpr (requires { Layout::inactiveLayers; }) { + return static_cast(Layout::inactiveLayers); + } else { + return std::uint64_t{0}; + } + }(); + + /// The layers whose clusters carry their own time box, not a readout + /// frame's record (`Layout::hitTimedLayers`, a bit per layer; none if the + /// layout declares none): the measurement producer keeps a cluster's box + /// there as its converter wrote it. ALICE 3's TOF, whose box is the bunch + /// crossing that ends at the hit's time, in TRKFT3TOF. Their readout frames + /// (`FrameTiming`) only lay out the grid's time blocks. + static constexpr std::uint64_t hitTimedLayers = [] { + if constexpr (requires { Layout::hitTimedLayers; }) { + return static_cast(Layout::hitTimedLayers); + } else { + return std::uint64_t{0}; + } + }(); + /// Layers are numbered barrel first, then discs. [[nodiscard]] static constexpr bool isBarrelLayer(LayerID layer) { return hasBarrel && std::cmp_less(layer, nBarrelLayers); } + /// Whether \a layer is inactive (`inactiveLayers`). + [[nodiscard]] static constexpr bool isInactiveLayer(LayerID layer) { return std::cmp_less(layer, 64) && ((inactiveLayers >> layer) & 1U) != 0U; } + + /// Whether \a layer's clusters carry their own time box (`hitTimedLayers`). + [[nodiscard]] static constexpr bool isHitTimedLayer(LayerID layer) { return std::cmp_less(layer, 64) && ((hitTimedLayers >> layer) & 1U) != 0U; } + /// Position of a disc layer within Layout::discLayers. [[nodiscard]] static constexpr std::size_t discIndex(LayerID layer) { return static_cast(layer) - static_cast(nBarrelLayers); } diff --git a/Detectors/GenericTracking/base/include/GenericTracking/Detectors/TRKFT3TOF.h b/Detectors/GenericTracking/base/include/GenericTracking/Detectors/TRKFT3TOF.h new file mode 100644 index 0000000000000..a68250431a04f --- /dev/null +++ b/Detectors/GenericTracking/base/include/GenericTracking/Detectors/TRKFT3TOF.h @@ -0,0 +1,318 @@ +// Copyright 2019-2020 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 TRKFT3TOF.h +/// \brief TRKFT3 with ALICE 3's inner and outer TOF as two inactive barrel +/// layers: the TOF clusters found, owned and fitted by the tracking. +/// +/// TRKFT3's layers in their original order, the iTOF (r 21.4 cm) +/// inserted as barrel layer 7 between ML layers 6 and 7, and the oTOF (r 92 cm) +/// as barrel layer 12 after the last OT layer: TRKFT3's layers 7-10 are 8-11 +/// here, its discs 11-22 are 13-24. Both TOF layers are inactive (LayerSpec.h). +/// Missing hits consume zero holes, and the TRK material slab boundaries +/// stay in place. The tracking schedule selects the iTOF seeding passes. +/// The default seeding mask leaves oTOF to the follower. +/// Sensor IDs are TRKFT3's, then the IOTOF chips at `kFirstTOFSensor` plus +/// O2's IOTOF chip ID (iTOF chips first). +/// +/// The TRK links are TRKFT3's renumbered: ML 6 -> ML 7 stays a direct link, +/// beside ML 6 -> iTOF -> ML 7. The links into and out of the TOF layers are +/// traced by `o2-gtrk-layer-links -d TRKFT3TOF`. The passives are TRKFT3's: +/// the iTOF's material stays passive 7's. +/// +/// A TOF cluster's time box is the bunch crossing that ends at its time, +/// [t - 1 BC, t] (WorkflowTRK/TRK.h, `tofClusters`): two TOF rows of a track +/// lie within 1 BC of each other, and the box never narrows a TRK readout +/// frame by more than the flight time to the TOF. + +#ifndef GTRK_DETECTORS_TRKFT3TOF_H_ +#define GTRK_DETECTORS_TRKFT3TOF_H_ + +#include "GenericTracking/Base/LayerSpec.h" +#include "GenericTracking/Detectors/TRKFT3.h" + +#include +#include + +namespace o2::gtrk::detectors +{ + +namespace trkft3tof +{ + +/// An IOTOF chip: O2's `ChipSpecificsParam` active matrix, 240 rows of +/// 100 um by 120 columns of 250 um, its frame centred on it; the plane at the +/// sensor's mid-plane (measurement depth 0). +inline constexpr SensorSpec kTOFChip{ + .shape = ShapeType::kRectangle, + .halfX = 1.2, + .halfY = 1.5, + .halfThickness = 0.0025, + .pitchX = 0.01, + .pitchY = 0.025, +}; +inline constexpr SensorSpec kInnerTOFChip = kTOFChip; +inline constexpr SensorSpec kOuterTOFChip = kTOFChip; + +/// TRKFT3's layer \a layer in TRKFT3TOF: 0-6 stay, 7-10 move past the iTOF, +/// the discs past the oTOF too. +[[nodiscard]] constexpr LayerID fromTRKFT3(LayerID layer) { return layer <= 6 ? layer : static_cast(layer <= 10 ? layer + 1 : layer + 2); } + +/// TRKFT3's overlap layers (LayerLinks.h `overlapLayers`) renumbered; none on +/// the TOF. +inline constexpr std::uint64_t kOverlapLayers = [] { + std::uint64_t layers = 0U; + for (int layer = 0; layer < 64; ++layer) { + if (((TRKFT3::overlapLayers >> layer) & 1U) != 0U) { + layers |= std::uint64_t{1} << fromTRKFT3(static_cast(layer)); + } + } + return layers; +}(); + +} // namespace trkft3tof + +struct TRKFT3TOF { + static constexpr const char* name = "TRKFT3TOF"; + static constexpr LayerID kInnerTOFLayer = 7; + static constexpr LayerID kOuterTOFLayer = 12; + static constexpr std::uint64_t inactiveLayers = (std::uint64_t{1} << kInnerTOFLayer) | (std::uint64_t{1} << kOuterTOFLayer); + /// The TOF's clusters carry their own time box, [t - 1 BC, t] + /// (WorkflowTRK/TRKTOF.h), not a readout frame's record. + static constexpr std::uint64_t hitTimedLayers = inactiveLayers; + static constexpr std::uint64_t defaultSeedingMask = ~(std::uint64_t{1} << kOuterTOFLayer); + /// The layers with overlapping sensors: TRKFT3's (`trkft3tof::kOverlapLayers`). + static constexpr std::uint64_t overlapLayers = trkft3tof::kOverlapLayers; + // clang-format off + static constexpr std::array barrelLayers{{ + {.sensorCount = 4, .sensor = trkft3::vdSensor(0)}, + {.sensorCount = 4, .sensor = trkft3::vdSensor(1)}, + {.sensorCount = 4, .sensor = trkft3::vdSensor(2)}, + {.sensorCount = 880, .sensor = trkft3::kChip}, + {.sensorCount = 1232, .sensor = trkft3::kChip}, + {.sensorCount = 1584, .sensor = trkft3::kChip}, + {.sensorCount = 2288, .sensor = trkft3::kChip}, + {.sensorCount = 2352, .sensor = trkft3tof::kInnerTOFChip}, + {.sensorCount = 3344, .sensor = trkft3::kChip}, + {.sensorCount = 10560, .sensor = trkft3::kChip}, + {.sensorCount = 13376, .sensor = trkft3::kChip}, + {.sensorCount = 17600, .sensor = trkft3::kChip}, + {.sensorCount = 56544, .sensor = trkft3tof::kOuterTOFChip}, + }}; + static constexpr std::array discLayers{{ + {.sensorCount = 440, .sensor = trkft3::kChip}, + {.sensorCount = 440, .sensor = trkft3::kChip}, + {.sensorCount = 440, .sensor = trkft3::kChip}, + {.sensorCount = 1864, .sensor = trkft3::kChip}, + {.sensorCount = 1864, .sensor = trkft3::kChip}, + {.sensorCount = 1864, .sensor = trkft3::kChip}, + {.sensorCount = 440, .sensor = trkft3::kChip}, + {.sensorCount = 440, .sensor = trkft3::kChip}, + {.sensorCount = 440, .sensor = trkft3::kChip}, + {.sensorCount = 1864, .sensor = trkft3::kChip}, + {.sensorCount = 1864, .sensor = trkft3::kChip}, + {.sensorCount = 1864, .sensor = trkft3::kChip}, + }}; + static constexpr std::array layerLinks{{ + {.from = 0, .to = 1, .sourceMin = -21.42, .sourceMax = 21.42, .skipsLayer = false}, // 0.9664 + {.from = 0, .to = 3, .sourceMin = -21.75, .sourceMax = 21.75, .skipsLayer = false}, // 0.0041 + {.from = 0, .to = 14, .sourceMin = -22.64, .sourceMax = -18.67, .skipsLayer = false}, // 0.0023 + {.from = 0, .to = 15, .sourceMin = -23.75, .sourceMax = -16.92, .skipsLayer = false}, // 0.0067 + {.from = 0, .to = 16, .sourceMin = -22.73, .sourceMax = -18.67, .skipsLayer = true}, // 0.0001 + {.from = 0, .to = 17, .sourceMin = -23.69, .sourceMax = -18.67, .skipsLayer = true}, // 0.0009 + {.from = 0, .to = 18, .sourceMin = -24.96, .sourceMax = -15.17, .skipsLayer = false}, // 0.0046 + {.from = 0, .to = 20, .sourceMin = 18.67, .sourceMax = 22.64, .skipsLayer = false}, // 0.0023 + {.from = 0, .to = 21, .sourceMin = 16.92, .sourceMax = 23.75, .skipsLayer = false}, // 0.0067 + {.from = 0, .to = 22, .sourceMin = 18.67, .sourceMax = 22.73, .skipsLayer = true}, // 0.0001 + {.from = 0, .to = 23, .sourceMin = 18.67, .sourceMax = 23.69, .skipsLayer = true}, // 0.0009 + {.from = 0, .to = 24, .sourceMin = 15.17, .sourceMax = 24.96, .skipsLayer = false}, // 0.0046 + {.from = 1, .to = 2, .sourceMin = -21.86, .sourceMax = 21.86, .skipsLayer = false}, // 0.8459 + {.from = 1, .to = 3, .sourceMin = -25.50, .sourceMax = 25.50, .skipsLayer = false}, // 0.0796 + {.from = 1, .to = 14, .sourceMin = -25.50, .sourceMax = -11.50, .skipsLayer = false}, // 0.0069 + {.from = 1, .to = 15, .sourceMin = -25.50, .sourceMax = -8.38, .skipsLayer = false}, // 0.0183 + {.from = 1, .to = 16, .sourceMin = -25.50, .sourceMax = -13.05, .skipsLayer = true}, // 0.0004 + {.from = 1, .to = 17, .sourceMin = -25.50, .sourceMax = -9.93, .skipsLayer = true}, // 0.0021 + {.from = 1, .to = 18, .sourceMin = -25.50, .sourceMax = -6.82, .skipsLayer = false}, // 0.0095 + {.from = 1, .to = 20, .sourceMin = 11.50, .sourceMax = 25.50, .skipsLayer = false}, // 0.0069 + {.from = 1, .to = 21, .sourceMin = 8.38, .sourceMax = 25.50, .skipsLayer = false}, // 0.0183 + {.from = 1, .to = 22, .sourceMin = 13.05, .sourceMax = 25.50, .skipsLayer = true}, // 0.0004 + {.from = 1, .to = 23, .sourceMin = 9.93, .sourceMax = 25.50, .skipsLayer = true}, // 0.0021 + {.from = 1, .to = 24, .sourceMin = 6.82, .sourceMax = 25.50, .skipsLayer = false}, // 0.0095 + {.from = 2, .to = 3, .sourceMin = -25.50, .sourceMax = 25.50, .skipsLayer = false}, // 0.9432 + {.from = 2, .to = 14, .sourceMin = -25.50, .sourceMax = -10.19, .skipsLayer = false}, // 0.0031 + {.from = 2, .to = 15, .sourceMin = -25.50, .sourceMax = -10.19, .skipsLayer = false}, // 0.0165 + {.from = 2, .to = 16, .sourceMin = -25.50, .sourceMax = -18.11, .skipsLayer = true}, // 0.0001 + {.from = 2, .to = 17, .sourceMin = -25.50, .sourceMax = -10.19, .skipsLayer = true}, // 0.0016 + {.from = 2, .to = 18, .sourceMin = -25.50, .sourceMax = -10.19, .skipsLayer = false}, // 0.0071 + {.from = 2, .to = 20, .sourceMin = 10.19, .sourceMax = 25.50, .skipsLayer = false}, // 0.0031 + {.from = 2, .to = 21, .sourceMin = 10.19, .sourceMax = 25.50, .skipsLayer = false}, // 0.0165 + {.from = 2, .to = 22, .sourceMin = 18.11, .sourceMax = 25.50, .skipsLayer = true}, // 0.0001 + {.from = 2, .to = 23, .sourceMin = 10.19, .sourceMax = 25.50, .skipsLayer = true}, // 0.0016 + {.from = 2, .to = 24, .sourceMin = 10.19, .sourceMax = 25.50, .skipsLayer = false}, // 0.0071 + {.from = 3, .to = 4, .sourceMin = -54.45, .sourceMax = 54.45, .skipsLayer = false}, // 0.8386 + {.from = 3, .to = 13, .sourceMin = -60.88, .sourceMax = -45.34, .skipsLayer = false}, // 0.0100 + {.from = 3, .to = 14, .sourceMin = -64.49, .sourceMax = -45.34, .skipsLayer = false}, // 0.0484 + {.from = 3, .to = 15, .sourceMin = -64.49, .sourceMax = -45.34, .skipsLayer = true}, // 0.0189 + {.from = 3, .to = 16, .sourceMin = -64.49, .sourceMax = -45.46, .skipsLayer = true}, // 0.0005 + {.from = 3, .to = 17, .sourceMin = -64.49, .sourceMax = -45.37, .skipsLayer = true}, // 0.0009 + {.from = 3, .to = 18, .sourceMin = -64.49, .sourceMax = -45.54, .skipsLayer = true}, // 0.0020 + {.from = 3, .to = 19, .sourceMin = 45.34, .sourceMax = 60.88, .skipsLayer = false}, // 0.0100 + {.from = 3, .to = 20, .sourceMin = 45.34, .sourceMax = 64.49, .skipsLayer = false}, // 0.0484 + {.from = 3, .to = 21, .sourceMin = 45.34, .sourceMax = 64.49, .skipsLayer = true}, // 0.0189 + {.from = 3, .to = 22, .sourceMin = 45.46, .sourceMax = 64.49, .skipsLayer = true}, // 0.0005 + {.from = 3, .to = 23, .sourceMin = 45.37, .sourceMax = 64.49, .skipsLayer = true}, // 0.0009 + {.from = 3, .to = 24, .sourceMin = 45.54, .sourceMax = 64.49, .skipsLayer = true}, // 0.0020 + {.from = 4, .to = 5, .sourceMin = -53.12, .sourceMax = 53.12, .skipsLayer = false}, // 0.7777 + {.from = 4, .to = 13, .sourceMin = -64.49, .sourceMax = -42.63, .skipsLayer = false}, // 0.0820 + {.from = 4, .to = 14, .sourceMin = -64.49, .sourceMax = -42.63, .skipsLayer = true}, // 0.0279 + {.from = 4, .to = 15, .sourceMin = -64.49, .sourceMax = -42.67, .skipsLayer = true}, // 0.0012 + {.from = 4, .to = 16, .sourceMin = -64.49, .sourceMax = -43.27, .skipsLayer = true}, // 0.0000 + {.from = 4, .to = 17, .sourceMin = -64.49, .sourceMax = -43.40, .skipsLayer = true}, // 0.0000 + {.from = 4, .to = 18, .sourceMin = -64.48, .sourceMax = -48.06, .skipsLayer = true}, // 0.0000 + {.from = 4, .to = 19, .sourceMin = 42.63, .sourceMax = 64.49, .skipsLayer = false}, // 0.0820 + {.from = 4, .to = 20, .sourceMin = 42.63, .sourceMax = 64.49, .skipsLayer = true}, // 0.0279 + {.from = 4, .to = 21, .sourceMin = 42.67, .sourceMax = 64.49, .skipsLayer = true}, // 0.0012 + {.from = 4, .to = 22, .sourceMin = 43.27, .sourceMax = 64.49, .skipsLayer = true}, // 0.0000 + {.from = 4, .to = 23, .sourceMin = 43.40, .sourceMax = 64.49, .skipsLayer = true}, // 0.0000 + {.from = 4, .to = 24, .sourceMin = 48.06, .sourceMax = 64.48, .skipsLayer = true}, // 0.0000 + {.from = 5, .to = 6, .sourceMin = -46.99, .sourceMax = 46.99, .skipsLayer = false}, // 0.5203 + {.from = 5, .to = 9, .sourceMin = -48.04, .sourceMax = 48.04, .skipsLayer = true}, // 0.0000 + {.from = 5, .to = 12, .sourceMin = -59.09, .sourceMax = 59.09, .skipsLayer = true}, // 0.0000 + {.from = 5, .to = 13, .sourceMin = -64.49, .sourceMax = -30.29, .skipsLayer = false}, // 0.2372 + {.from = 5, .to = 14, .sourceMin = -64.49, .sourceMax = -30.32, .skipsLayer = true}, // 0.0026 + {.from = 5, .to = 15, .sourceMin = -64.49, .sourceMax = -31.27, .skipsLayer = true}, // 0.0000 + {.from = 5, .to = 16, .sourceMin = -64.48, .sourceMax = -32.10, .skipsLayer = true}, // 0.0000 + {.from = 5, .to = 17, .sourceMin = -63.91, .sourceMax = -34.79, .skipsLayer = true}, // 0.0000 + {.from = 5, .to = 18, .sourceMin = -58.92, .sourceMax = -32.99, .skipsLayer = true}, // 0.0000 + {.from = 5, .to = 19, .sourceMin = 30.29, .sourceMax = 64.49, .skipsLayer = false}, // 0.2372 + {.from = 5, .to = 20, .sourceMin = 30.32, .sourceMax = 64.49, .skipsLayer = true}, // 0.0026 + {.from = 5, .to = 21, .sourceMin = 31.27, .sourceMax = 64.49, .skipsLayer = true}, // 0.0000 + {.from = 5, .to = 22, .sourceMin = 32.10, .sourceMax = 64.48, .skipsLayer = true}, // 0.0000 + {.from = 5, .to = 23, .sourceMin = 34.79, .sourceMax = 63.91, .skipsLayer = true}, // 0.0000 + {.from = 5, .to = 24, .sourceMin = 32.99, .sourceMax = 58.92, .skipsLayer = true}, // 0.0000 + {.from = 6, .to = 7, .sourceMin = -59.76, .sourceMax = 59.76, .skipsLayer = false}, // 0.7981 + {.from = 6, .to = 8, .sourceMin = -47.81, .sourceMax = 47.81, .skipsLayer = false}, // 0.1654 + {.from = 6, .to = 9, .sourceMin = -64.49, .sourceMax = 64.49, .skipsLayer = false}, // 0.1386 + {.from = 6, .to = 12, .sourceMin = -64.46, .sourceMax = 64.46, .skipsLayer = true}, // 0.0000 + {.from = 6, .to = 13, .sourceMin = -64.49, .sourceMax = -25.80, .skipsLayer = false}, // 0.3430 + {.from = 6, .to = 14, .sourceMin = -64.49, .sourceMax = -26.95, .skipsLayer = true}, // 0.0011 + {.from = 6, .to = 15, .sourceMin = -64.45, .sourceMax = -37.92, .skipsLayer = true}, // 0.0000 + {.from = 6, .to = 16, .sourceMin = -64.49, .sourceMax = -30.59, .skipsLayer = false}, // 0.0038 + {.from = 6, .to = 17, .sourceMin = -64.48, .sourceMax = -33.05, .skipsLayer = true}, // 0.0001 + {.from = 6, .to = 18, .sourceMin = -64.46, .sourceMax = -36.83, .skipsLayer = true}, // 0.0000 + {.from = 6, .to = 19, .sourceMin = 25.80, .sourceMax = 64.49, .skipsLayer = false}, // 0.3430 + {.from = 6, .to = 20, .sourceMin = 26.95, .sourceMax = 64.49, .skipsLayer = true}, // 0.0011 + {.from = 6, .to = 21, .sourceMin = 37.92, .sourceMax = 64.45, .skipsLayer = true}, // 0.0000 + {.from = 6, .to = 22, .sourceMin = 30.59, .sourceMax = 64.49, .skipsLayer = false}, // 0.0038 + {.from = 6, .to = 23, .sourceMin = 33.05, .sourceMax = 64.48, .skipsLayer = true}, // 0.0001 + {.from = 6, .to = 24, .sourceMin = 36.83, .sourceMax = 64.46, .skipsLayer = true}, // 0.0000 + {.from = 7, .to = 8, .sourceMin = -50.76, .sourceMax = 50.76, .skipsLayer = false}, // 0.2092 + {.from = 7, .to = 9, .sourceMin = -63.91, .sourceMax = 63.91, .skipsLayer = false}, // 0.1751 + {.from = 7, .to = 12, .sourceMin = -63.91, .sourceMax = 63.91, .skipsLayer = true}, // 0.0000 + {.from = 7, .to = 13, .sourceMin = -63.91, .sourceMax = -31.08, .skipsLayer = false}, // 0.3028 + {.from = 7, .to = 14, .sourceMin = -63.91, .sourceMax = -32.29, .skipsLayer = true}, // 0.0005 + {.from = 7, .to = 15, .sourceMin = -63.91, .sourceMax = -44.64, .skipsLayer = true}, // 0.0000 + {.from = 7, .to = 16, .sourceMin = -63.91, .sourceMax = -35.97, .skipsLayer = false}, // 0.0045 + {.from = 7, .to = 17, .sourceMin = -63.91, .sourceMax = -38.60, .skipsLayer = true}, // 0.0001 + {.from = 7, .to = 18, .sourceMin = -63.91, .sourceMax = -42.70, .skipsLayer = true}, // 0.0000 + {.from = 7, .to = 19, .sourceMin = 31.08, .sourceMax = 63.92, .skipsLayer = false}, // 0.3028 + {.from = 7, .to = 20, .sourceMin = 32.29, .sourceMax = 63.92, .skipsLayer = true}, // 0.0005 + {.from = 7, .to = 21, .sourceMin = 44.64, .sourceMax = 63.91, .skipsLayer = true}, // 0.0000 + {.from = 7, .to = 22, .sourceMin = 35.97, .sourceMax = 63.92, .skipsLayer = false}, // 0.0045 + {.from = 7, .to = 23, .sourceMin = 38.60, .sourceMax = 63.91, .skipsLayer = true}, // 0.0001 + {.from = 7, .to = 24, .sourceMin = 42.70, .sourceMax = 63.91, .skipsLayer = true}, // 0.0000 + {.from = 8, .to = 9, .sourceMin = -64.49, .sourceMax = 64.49, .skipsLayer = false}, // 0.9844 + {.from = 8, .to = 13, .sourceMin = -64.49, .sourceMax = -47.69, .skipsLayer = false}, // 0.0068 + {.from = 8, .to = 16, .sourceMin = -64.48, .sourceMax = -59.59, .skipsLayer = false}, // 0.0010 + {.from = 8, .to = 19, .sourceMin = 47.69, .sourceMax = 64.49, .skipsLayer = false}, // 0.0068 + {.from = 8, .to = 22, .sourceMin = 59.59, .sourceMax = 64.48, .skipsLayer = false}, // 0.0010 + {.from = 9, .to = 10, .sourceMin = -101.31, .sourceMax = 101.31, .skipsLayer = false}, // 0.1297 + {.from = 9, .to = 12, .sourceMin = -128.88, .sourceMax = 128.88, .skipsLayer = false}, // 0.0490 + {.from = 9, .to = 16, .sourceMin = -128.88, .sourceMax = -70.15, .skipsLayer = false}, // 0.4250 + {.from = 9, .to = 17, .sourceMin = -128.88, .sourceMax = -77.47, .skipsLayer = true}, // 0.0101 + {.from = 9, .to = 18, .sourceMin = -128.88, .sourceMax = -87.08, .skipsLayer = true}, // 0.0001 + {.from = 9, .to = 22, .sourceMin = 70.15, .sourceMax = 128.88, .skipsLayer = false}, // 0.4250 + {.from = 9, .to = 23, .sourceMin = 77.47, .sourceMax = 128.88, .skipsLayer = true}, // 0.0101 + {.from = 9, .to = 24, .sourceMin = 87.08, .sourceMax = 128.88, .skipsLayer = true}, // 0.0001 + {.from = 10, .to = 11, .sourceMin = -101.25, .sourceMax = 101.25, .skipsLayer = false}, // 0.1171 + {.from = 10, .to = 12, .sourceMin = -128.88, .sourceMax = 128.88, .skipsLayer = false}, // 0.3932 + {.from = 10, .to = 16, .sourceMin = -128.88, .sourceMax = -91.29, .skipsLayer = false}, // 0.4406 + {.from = 10, .to = 17, .sourceMin = -128.88, .sourceMax = -110.80, .skipsLayer = true}, // 0.0009 + {.from = 10, .to = 22, .sourceMin = 91.29, .sourceMax = 128.88, .skipsLayer = false}, // 0.4406 + {.from = 10, .to = 23, .sourceMin = 110.80, .sourceMax = 128.88, .skipsLayer = true}, // 0.0009 + {.from = 11, .to = 12, .sourceMin = -128.88, .sourceMax = 128.88, .skipsLayer = false}, // 1.0000 + {.from = 13, .to = 9, .sourceMin = 23.87, .sourceMax = 35.17, .skipsLayer = false}, // 0.0952 + {.from = 13, .to = 12, .sourceMin = 19.67, .sourceMax = 30.44, .skipsLayer = true}, // 0.0001 + {.from = 13, .to = 14, .sourceMin = 9.50, .sourceMax = 33.31, .skipsLayer = false}, // 0.7973 + {.from = 13, .to = 15, .sourceMin = 9.50, .sourceMax = 30.66, .skipsLayer = true}, // 0.0066 + {.from = 13, .to = 16, .sourceMin = 9.56, .sourceMax = 35.14, .skipsLayer = false}, // 0.0969 + {.from = 13, .to = 17, .sourceMin = 9.53, .sourceMax = 34.13, .skipsLayer = true}, // 0.0039 + {.from = 13, .to = 18, .sourceMin = 9.96, .sourceMax = 32.62, .skipsLayer = true}, // 0.0001 + {.from = 14, .to = 9, .sourceMin = 33.24, .sourceMax = 35.16, .skipsLayer = false}, // 0.0000 + {.from = 14, .to = 12, .sourceMin = 23.52, .sourceMax = 35.04, .skipsLayer = true}, // 0.0000 + {.from = 14, .to = 15, .sourceMin = 9.50, .sourceMax = 33.83, .skipsLayer = false}, // 0.8259 + {.from = 14, .to = 16, .sourceMin = 10.57, .sourceMax = 35.17, .skipsLayer = false}, // 0.1645 + {.from = 14, .to = 17, .sourceMin = 9.57, .sourceMax = 35.16, .skipsLayer = true}, // 0.0088 + {.from = 14, .to = 18, .sourceMin = 9.55, .sourceMax = 34.99, .skipsLayer = true}, // 0.0008 + {.from = 15, .to = 12, .sourceMin = 29.04, .sourceMax = 34.16, .skipsLayer = true}, // 0.0000 + {.from = 15, .to = 16, .sourceMin = 12.06, .sourceMax = 35.17, .skipsLayer = false}, // 0.6962 + {.from = 15, .to = 17, .sourceMin = 9.90, .sourceMax = 35.16, .skipsLayer = false}, // 0.1845 + {.from = 15, .to = 18, .sourceMin = 9.51, .sourceMax = 35.05, .skipsLayer = false}, // 0.1193 + {.from = 16, .to = 12, .sourceMin = 36.91, .sourceMax = 71.13, .skipsLayer = false}, // 0.0563 + {.from = 16, .to = 17, .sourceMin = 15.18, .sourceMax = 68.75, .skipsLayer = false}, // 0.9588 + {.from = 16, .to = 18, .sourceMin = 15.18, .sourceMax = 63.29, .skipsLayer = true}, // 0.0412 + {.from = 17, .to = 12, .sourceMin = 45.30, .sourceMax = 71.14, .skipsLayer = false}, // 0.0630 + {.from = 17, .to = 18, .sourceMin = 15.18, .sourceMax = 68.29, .skipsLayer = false}, // 1.0000 + {.from = 18, .to = 12, .sourceMin = 56.58, .sourceMax = 71.14, .skipsLayer = false}, // 1.0000 + {.from = 19, .to = 9, .sourceMin = 23.87, .sourceMax = 35.17, .skipsLayer = false}, // 0.0952 + {.from = 19, .to = 12, .sourceMin = 19.67, .sourceMax = 30.44, .skipsLayer = true}, // 0.0001 + {.from = 19, .to = 20, .sourceMin = 9.50, .sourceMax = 33.31, .skipsLayer = false}, // 0.7973 + {.from = 19, .to = 21, .sourceMin = 9.50, .sourceMax = 30.66, .skipsLayer = true}, // 0.0066 + {.from = 19, .to = 22, .sourceMin = 9.56, .sourceMax = 35.14, .skipsLayer = false}, // 0.0969 + {.from = 19, .to = 23, .sourceMin = 9.53, .sourceMax = 34.13, .skipsLayer = true}, // 0.0039 + {.from = 19, .to = 24, .sourceMin = 9.96, .sourceMax = 32.62, .skipsLayer = true}, // 0.0001 + {.from = 20, .to = 9, .sourceMin = 33.24, .sourceMax = 35.16, .skipsLayer = false}, // 0.0000 + {.from = 20, .to = 12, .sourceMin = 23.52, .sourceMax = 35.04, .skipsLayer = true}, // 0.0000 + {.from = 20, .to = 21, .sourceMin = 9.50, .sourceMax = 33.83, .skipsLayer = false}, // 0.8259 + {.from = 20, .to = 22, .sourceMin = 10.57, .sourceMax = 35.17, .skipsLayer = false}, // 0.1645 + {.from = 20, .to = 23, .sourceMin = 9.57, .sourceMax = 35.16, .skipsLayer = true}, // 0.0088 + {.from = 20, .to = 24, .sourceMin = 9.55, .sourceMax = 34.99, .skipsLayer = true}, // 0.0008 + {.from = 21, .to = 12, .sourceMin = 29.04, .sourceMax = 34.16, .skipsLayer = true}, // 0.0000 + {.from = 21, .to = 22, .sourceMin = 12.06, .sourceMax = 35.17, .skipsLayer = false}, // 0.6962 + {.from = 21, .to = 23, .sourceMin = 9.90, .sourceMax = 35.16, .skipsLayer = false}, // 0.1845 + {.from = 21, .to = 24, .sourceMin = 9.51, .sourceMax = 35.05, .skipsLayer = false}, // 0.1193 + {.from = 22, .to = 23, .sourceMin = 15.18, .sourceMax = 68.75, .skipsLayer = false}, // 0.9588 + {.from = 22, .to = 24, .sourceMin = 15.18, .sourceMax = 63.29, .skipsLayer = true}, // 0.0412 + {.from = 23, .to = 24, .sourceMin = 15.18, .sourceMax = 68.29, .skipsLayer = false}, // 1.0000 + }}; + static constexpr std::array passives{{ + {.kind = PassiveSpec::Kind::kBarrel, .position = 0.4899, .bandLow = 0.0000, .bandHigh = 0.4999, .low = -25.00, .high = 25.00, .x2X0 = 2.224e-03}, + {.kind = PassiveSpec::Kind::kBarrel, .position = 0.8002, .bandLow = 0.5096, .bandHigh = 1.1999, .low = -25.00, .high = 25.00, .x2X0 = 1.228e-03}, + {.kind = PassiveSpec::Kind::kBarrel, .position = 1.7708, .bandLow = 1.2096, .bandHigh = 2.5000, .low = -25.00, .high = 25.00, .x2X0 = 9.985e-04}, + {.kind = PassiveSpec::Kind::kBarrel, .position = 3.7955, .bandLow = 2.5096, .bandHigh = 6.8657, .low = -63.98, .high = 63.98, .x2X0 = 1.132e-02}, + {.kind = PassiveSpec::Kind::kBarrel, .position = 7.9710, .bandLow = 7.8977, .bandHigh = 8.8055, .low = -63.98, .high = 63.98, .x2X0 = 3.692e-04}, + {.kind = PassiveSpec::Kind::kBarrel, .position = 10.0133, .bandLow = 9.8542, .bandHigh = 11.7623, .low = -63.98, .high = 63.98, .x2X0 = 4.094e-04}, + {.kind = PassiveSpec::Kind::kBarrel, .position = 13.8492, .bandLow = 12.7722, .bandHigh = 18.7300, .low = -63.98, .high = 63.98, .x2X0 = 4.863e-04}, + {.kind = PassiveSpec::Kind::kBarrel, .position = 21.2092, .bandLow = 20.1379, .bandHigh = 29.9999, .low = -63.98, .high = 63.98, .x2X0 = 2.027e-02}, + {.kind = PassiveSpec::Kind::kBarrel, .position = 38.2067, .bandLow = 31.0792, .bandHigh = 44.8000, .low = -128.38, .high = 128.38, .x2X0 = 2.557e-02}, + {.kind = PassiveSpec::Kind::kBarrel, .position = 52.1226, .bandLow = 45.3527, .bandHigh = 59.8000, .low = -128.38, .high = 128.38, .x2X0 = 4.899e-04}, + {.kind = PassiveSpec::Kind::kBarrel, .position = 69.6851, .bandLow = 60.2898, .bandHigh = 79.8000, .low = -128.38, .high = 128.38, .x2X0 = 6.376e-04}, + }}; + // clang-format on + static constexpr int nSensors = TRKFT3::nSensors + 2352 + 56544; + static constexpr int kFirstDiscSensor = TRKFT3::kFirstDiscSensor; + /// The first TOF sensor's ID: O2's IOTOF chip 0, after every TRKFT3 chip. + static constexpr int kFirstTOFSensor = TRKFT3::nSensors; +}; + +} // namespace o2::gtrk::detectors + +#endif // GTRK_DETECTORS_TRKFT3TOF_H_ diff --git a/Detectors/GenericTracking/study/CMakeLists.txt b/Detectors/GenericTracking/study/CMakeLists.txt index 7f9dbb593687a..3c137c1a05acd 100644 --- a/Detectors/GenericTracking/study/CMakeLists.txt +++ b/Detectors/GenericTracking/study/CMakeLists.txt @@ -50,7 +50,7 @@ o2_target_root_dictionary(GTrkStudy LINKDEF src/GTrkStudyLinkDef.h) # The sink, one unit per detector: each instantiates the tracker and its QA. -foreach(detector ITS MFT TRKFT3) +foreach(detector ITS MFT TRKFT3 TRKFT3TOF) add_library(gtrk_sink_${detector} OBJECT src/MeasurementSinkSpec.cxx) set_property(TARGET gtrk_sink_${detector} PROPERTY POSITION_INDEPENDENT_CODE ON) target_compile_definitions(gtrk_sink_${detector} PRIVATE GTRK_SINK_DETECTOR=${detector}) @@ -72,12 +72,12 @@ o2_add_executable(mft-study-workflow o2_add_executable(trk-study-workflow SOURCES tools/gtrk-trk-study-workflow.cxx COMPONENT_NAME gtrk - PUBLIC_LINK_LIBRARIES O2::GTrkStudy O2::DetectorsRaw O2::TRKWorkflow) + PUBLIC_LINK_LIBRARIES O2::GTrkStudy O2::DetectorsRaw O2::TRKWorkflow O2::IOTOFWorkflow) # One unit per detector's run (TrackBench.h), the options and the dispatch in # trackBench.cxx: the detectors compile in parallel. o2_add_executable(track-bench - SOURCES tools/trackBench.cxx tools/trackBenchITS.cxx tools/trackBenchMFT.cxx tools/trackBenchTRKFT3.cxx + SOURCES tools/trackBench.cxx tools/trackBenchITS.cxx tools/trackBenchMFT.cxx tools/trackBenchTRKFT3.cxx tools/trackBenchTRKFT3TOF.cxx COMPONENT_NAME gtrk PUBLIC_LINK_LIBRARIES O2::GTrkStudy O2::Steer O2::CCDB Boost::program_options TARGETVARNAME benchTarget) diff --git a/Detectors/GenericTracking/study/include/GenericTracking/Study/Alice/Hits.h b/Detectors/GenericTracking/study/include/GenericTracking/Study/Alice/Hits.h index 7ecf879b54b3f..696704f277233 100644 --- a/Detectors/GenericTracking/study/include/GenericTracking/Study/Alice/Hits.h +++ b/Detectors/GenericTracking/study/include/GenericTracking/Study/Alice/Hits.h @@ -20,6 +20,7 @@ #include "GenericTracking/Detectors/ITS.h" #include "GenericTracking/Detectors/MFT.h" #include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" #include #include @@ -45,9 +46,10 @@ enum class Chips : std::uint8_t { kITS, kMFT, kTRK }; -/// Whose MC files a layout's are. +/// Whose MC files a layout's are: TRKFT3TOF's are the TRK's and FT3's, its +/// TRK sensors TRKFT3's (the TOF's hits are not read). template - requires std::same_as || std::same_as || std::same_as + requires std::same_as || std::same_as || std::same_as || std::same_as [[nodiscard]] constexpr Chips chipsOf() { if constexpr (std::same_as) { diff --git a/Detectors/GenericTracking/study/src/MCVertexReaderSpec.cxx b/Detectors/GenericTracking/study/src/MCVertexReaderSpec.cxx index f047f109d7676..de5c6dad449aa 100644 --- a/Detectors/GenericTracking/study/src/MCVertexReaderSpec.cxx +++ b/Detectors/GenericTracking/study/src/MCVertexReaderSpec.cxx @@ -14,6 +14,7 @@ #include "GenericTracking/Detectors/ITS.h" #include "GenericTracking/Detectors/MFT.h" #include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" #include "GenericTracking/Workflow/DataSpecs.h" #include "GenericTracking/Workflow/GridConfig.h" #include "GenericTracking/Workflow/RecoParam.h" @@ -171,5 +172,6 @@ DataProcessorSpec getMCVertexReaderSpec() template DataProcessorSpec getMCVertexReaderSpec(); template DataProcessorSpec getMCVertexReaderSpec(); template DataProcessorSpec getMCVertexReaderSpec(); +template DataProcessorSpec getMCVertexReaderSpec(); } // namespace o2::gtrk::study diff --git a/Detectors/GenericTracking/study/src/MeasurementSinkSpec.cxx b/Detectors/GenericTracking/study/src/MeasurementSinkSpec.cxx index c7c0918538de6..1edbbc7c376ee 100644 --- a/Detectors/GenericTracking/study/src/MeasurementSinkSpec.cxx +++ b/Detectors/GenericTracking/study/src/MeasurementSinkSpec.cxx @@ -18,6 +18,7 @@ #include "GenericTracking/Detectors/ITS.h" #include "GenericTracking/Detectors/MFT.h" #include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" #include "GenericTracking/Tracking/Iteration.h" #include "GenericTracking/Tracking/LayerMaterial.h" #include "GenericTracking/Tracking/MeasurementGridBuilder.h" @@ -112,6 +113,8 @@ namespace #error "GTRK_SINK_DETECTOR names the sink's detector" #endif using Det = detectors::GTRK_SINK_DETECTOR; +/// ALICE 3's tracker, with or without its TOF layers: TRK's and FT3's MC files. +constexpr bool kAlice3Tracker = std::is_same_v || std::is_same_v; using Frame = TimeFrame; using Tracklets = StageOutput; using Controller = workflow::TrackingInterface::Controller; @@ -2918,7 +2921,7 @@ class MeasurementSinkTask : public Task // The MC hits: the pulls with --o2-tracks, the true kinks behind the // lost pairs and the tracks found incomplete, and the QA's outward legs. if (mUseMC) { - mHits = openHits(ic.options().get("mc-hits"), std::is_same_v ? ic.options().get("mc-ft3-hits") : ""); + mHits = openHits(ic.options().get("mc-hits"), kAlice3Tracker ? ic.options().get("mc-ft3-hits") : ""); if (mHits) { mHitIndex.emplace(*mHits); } @@ -3308,7 +3311,7 @@ class MeasurementSinkTask : public Task const std::string name = mQAOutput->GetFile()->GetName(); if (mInterface.configured()) { // The MC events: the signal source's, as the truth is. - streamRun(*mQAOutput, workflow::iterationCount(recoParam()), etaReach(PlacedEnvelopes::all()), findableRule(), mKinematics ? mKinematics->getNEvents(0) : 0U, std::is_same_v ? 0U : (std::uint64_t{1} << Detector::nLayers) - 1U); + streamRun(*mQAOutput, workflow::iterationCount(recoParam()), etaReach(PlacedEnvelopes::all()), findableRule(), mKinematics ? mKinematics->getNEvents(0) : 0U, kAlice3Tracker ? 0U : (std::uint64_t{1} << Detector::nLayers) - 1U); } mQAOutput->Close(); mQAOutput.reset(); @@ -3594,7 +3597,7 @@ class MeasurementSinkTask : public Task layers.push_back(crossing.layer); } } - if constexpr (std::is_same_v) { + if constexpr (kAlice3Tracker) { if (std::cmp_greater_equal(outward[id], findableRule().minLayers)) { for (const auto& crossing : leg) { outwardMasks[id] |= std::uint64_t{1} << crossing.layer; @@ -3614,7 +3617,7 @@ class MeasurementSinkTask : public Task } const auto& helix = label->second.helix; auto& extra = extras[id]; - if constexpr (std::is_same_v) { + if constexpr (kAlice3Tracker) { if (const auto mask = outwardMasks.find(id); mask != outwardMasks.end()) { extra.expectedLayerMask = mask->second; } @@ -4488,7 +4491,7 @@ class MeasurementSinkTask : public Task { if constexpr (std::is_same_v) { return "sgn_HitsMFT.root"; - } else if constexpr (std::is_same_v) { + } else if constexpr (kAlice3Tracker) { return "sgn_HitsTRK.root"; } else { return "sgn_HitsITS.root"; @@ -4520,7 +4523,7 @@ DataProcessorSpec getMeasurementSinkSpec(bool useMC, bool withVertices, Tra .algorithm = AlgorithmSpec{adaptFromTask(useMC, withVertices, products, conditions)}, .options = Options{{"collision-context", VariantType::String, "collisioncontext.root", {"collision context and MC-event mapping"}}, {"input-dir", VariantType::String, "none", {"input directory"}}, {"tracklet-truth-output", VariantType::String, "gtrk_tracklet_truth.csv", {"per-link pT and cot(theta) truth breakdown; empty disables"}}, {"dump-tracking-input", VariantType::String, "", {"write one timeframe's tracking input here, for o2-gtrk-track-bench"}}, {"dump-timeframe", VariantType::Int, 0, {"which timeframe --dump-tracking-input writes, counting from 0"}}, {"dump-only", VariantType::Bool, false, {"with --dump-tracking-input, the dumped timeframe is not tracked"}}, {"qa-output", VariantType::String, "", {"the MC truth QA as ROOT trees; empty disables"}}, {"outward-momenta", VariantType::Bool, false, {"with --qa-output and MC hits, the momenta tree: |p| along the outward leg of every findable electron and every 16th pion"}}, {"truth-study", VariantType::String, "", {"truth studies, :: separated by ',': module gsf, species, decaycensus or decayfit, source truth (the particles' own rows) or tracks (the good tracks' rows), a .csv or .root path; with MC and its hits"}}, {"truth-select", VariantType::String, "", {"the truth studies' particles: key=value items separated by ';' -- origins=primary+decay+material, pdg=11+211, minPt=, minRows=, layers=, findable"}}, {"no-truth-reports", VariantType::Bool, false, {"with MC, no truth reports in the log (stages, true roads' chi2, fake anatomy): for the QA alone"}}, {"findable-min-pt", VariantType::Double, 0.1, {"the findable rule's pT floor [GeV]: the QA, the comparisons, the funnel"}}, {"o2-tracks", VariantType::String, "", {"O2's tracks of the same clusters (o2trac_its.root, mfttracks.root), compared under one set of truth rules"}}, {"mc-hits", VariantType::String, hitFileName(), {"O2's MC hits, for the pulls, the true kinks and the QA's outward legs"}}}, }; - if constexpr (std::is_same_v) { + if constexpr (kAlice3Tracker) { spec.options.push_back({"mc-ft3-hits", VariantType::String, "sgn_HitsFT3.root", {"O2's MC hits of FT3's discs, with --mc-hits TRK's"}}); } return spec; diff --git a/Detectors/GenericTracking/study/tools/TrackBench.h b/Detectors/GenericTracking/study/tools/TrackBench.h index c5cc4fe617b04..72228440c0bbe 100644 --- a/Detectors/GenericTracking/study/tools/TrackBench.h +++ b/Detectors/GenericTracking/study/tools/TrackBench.h @@ -23,6 +23,7 @@ #include "GenericTracking/Detectors/ITS.h" #include "GenericTracking/Detectors/MFT.h" #include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" #include "GenericTracking/Tracking/CpuBackend.h" #include "GenericTracking/Tracking/MeasurementGrid.h" #include "GenericTracking/Tracking/MeasurementGridBuilder.h" @@ -1885,7 +1886,7 @@ int track(const Options& options) // NOLINT(readability-function-size): the benc // (Conditions::orbitsPerTimeframe): its GRPECS's; ALICE 3's simulation // writes none, and the dump's HBFUtils is its. int orbitsPerTimeframe = 0; - if constexpr (std::same_as) { + if constexpr (std::same_as || std::same_as) { orbitsPerTimeframe = o2::raw::HBFUtils::Instance().getNOrbitsPerTF(); } else { const auto* ecs = ccdb.get("GLO/Config/GRPECS"); @@ -1971,7 +1972,7 @@ int track(const Options& options) // NOLINT(readability-function-size): the benc throw std::runtime_error("--complete-anatomy and --truth-study need the MC truth"); } if (!options.hits.empty()) { - hitFile = std::make_unique(options.hits, study::chipsOf(), std::is_same_v ? options.ft3Hits : std::string{}); + hitFile = std::make_unique(options.hits, study::chipsOf(), std::is_same_v || std::is_same_v ? options.ft3Hits : std::string{}); hitIndex.emplace(*hitFile); } particleChains.emplace(study::ParticleChains::build(truth->rows, truth->particles, frame, hitIndex ? &*hitIndex : nullptr, *studyArena)); @@ -2777,6 +2778,7 @@ int track(const Options& options) // NOLINT(readability-function-size): the benc extern template int track(const Options& options); extern template int track(const Options& options); extern template int track(const Options& options); +extern template int track(const Options& options); } // namespace o2::gtrk::study diff --git a/Detectors/GenericTracking/study/tools/gtrk-trk-study-workflow.cxx b/Detectors/GenericTracking/study/tools/gtrk-trk-study-workflow.cxx index 099418be1cb2b..d99591c21a9d5 100644 --- a/Detectors/GenericTracking/study/tools/gtrk-trk-study-workflow.cxx +++ b/Detectors/GenericTracking/study/tools/gtrk-trk-study-workflow.cxx @@ -10,7 +10,8 @@ // or submit itself to any jurisdiction. /// \file gtrk-trk-study-workflow.cxx -/// \brief ALICE 3's TRK and FT3 clusters from O2's readers or upstream, with the study's sink (StudyWorkflow.h). +/// \brief ALICE 3's TRK and FT3 clusters from O2's readers or upstream, with the study's sink (StudyWorkflow.h); +/// with `--tof-layers` the TRKFT3TOF layout, the IOTOF's clusters too. #include "StudyWorkflow.h" @@ -25,11 +26,17 @@ using namespace o2::framework; void customize(std::vector& policies) { o2::raw::HBFUtilsInitializer::addNewTimeSliceCallback(policies); } // NOLINTNEXTLINE(misc-use-internal-linkage) -void customize(std::vector& workflowOptions) { o2::gtrk::study::addStudyOptions(workflowOptions); } +void customize(std::vector& workflowOptions) +{ + o2::gtrk::study::addStudyOptions(workflowOptions); + workflowOptions.push_back(ConfigParamSpec{"tof-layers", VariantType::Bool, false, {"the TRKFT3TOF layout: the IOTOF's clusters tracked as the TRK's"}}); +} #include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" #include "Framework/runDataProcessing.h" // IWYU pragma: keep +#include "IOTOFWorkflow/ClusterReaderSpec.h" #include "TRKWorkflow/ClusterReaderSpec.h" #include @@ -39,7 +46,9 @@ WorkflowSpec defineDataProcessing(const ConfigContext& context) o2::conf::ConfigurableParam::updateFromString(context.options().get("configKeyValues")); const bool useMC = !context.options().get("disable-mc"); - auto specs = o2::gtrk::study::studyChain(context, {o2::trk::getTRKClusterReaderSpec(useMC), o2::trk::getFT3ClusterReaderSpec(useMC)}); + auto specs = context.options().get("tof-layers") + ? o2::gtrk::study::studyChain(context, {o2::trk::getTRKClusterReaderSpec(useMC), o2::trk::getFT3ClusterReaderSpec(useMC), o2::iotof::getIOTOFClusterReaderSpec(useMC)}) + : o2::gtrk::study::studyChain(context, {o2::trk::getTRKClusterReaderSpec(useMC), o2::trk::getFT3ClusterReaderSpec(useMC)}); const o2::raw::HBFUtilsInitializer hbfIni(context, specs); diff --git a/Detectors/GenericTracking/study/tools/trackBench.cxx b/Detectors/GenericTracking/study/tools/trackBench.cxx index 44625f7dadf82..c7280d9359153 100644 --- a/Detectors/GenericTracking/study/tools/trackBench.cxx +++ b/Detectors/GenericTracking/study/tools/trackBench.cxx @@ -56,9 +56,9 @@ static int run(int argc, char** argv) { Options options; bpo::options_description description("Track a dumped tracking input"); - description.add_options() // - ("help,h", "this message") // - ("detector,d", bpo::value(&options.detector)->required(), "its, mft or trk: the ITS, the MFT or ALICE 3's barrel on O2's clusters") // + description.add_options() // + ("help,h", "this message") // + ("detector,d", bpo::value(&options.detector)->required(), "its, mft, trk or trktof: the ITS, the MFT, ALICE 3's barrel on O2's clusters, or with its TOF layers") // ("ccdb-url", bpo::value(&options.ccdbUrl)->default_value(o2::base::NameConf::getCCDBServer()), "the conditions' CCDB, e.g. file:///ccdb for its snapshots: the aligned geometry (GLO/Config/GeometryAligned), the field (GLO/Config/GRPMagField, not " "for trk) and the material LUT (GLO/Param/MatLUT, MFT/Param/MatLUT, TRK/Param/MatLUT), the sink's conditions") // @@ -238,14 +238,13 @@ static int run(int argc, char** argv) // The trial's keys and --threads go on in track, after the dump's own grid // is known. - // The detector's parameter: GTRKRecoITS, GTRKRecoMFT, GTRKRecoTRK. std::string detector = options.detector; std::ranges::transform(detector, detector.begin(), [](unsigned char c) { return static_cast(std::toupper(c)); }); loadConfiguration(options.config.empty() ? options.input + ".ini" : options.config, "GTRKReco" + detector); // The conditions' CCDB: TrackBench.h reads the geometry and the material LUT from it too. o2::ccdb::BasicCCDBManager::instance().setURL(options.ccdbUrl); double bz = 0.; - if (options.detector == "trk") { + if (options.detector == "trk" || options.detector == "trktof") { // ALICE 3's field is not in its GRP: O2's ALICE 3 field, as the workflow's conditions take it. bz = alice::alice3BzKiloGauss(); o2::base::Propagator::Instance(true)->setNominalBz(static_cast(bz)); @@ -263,7 +262,10 @@ static int run(int argc, char** argv) if (options.detector == "trk") { return track(options); } - throw std::runtime_error("no detector called '" + options.detector + "'; its, mft or trk"); + if (options.detector == "trktof") { + return track(options); + } + throw std::runtime_error("no detector called '" + options.detector + "'; its, mft, trk or trktof"); } } // namespace o2::gtrk::study diff --git a/Detectors/GenericTracking/study/tools/trackBenchTRKFT3TOF.cxx b/Detectors/GenericTracking/study/tools/trackBenchTRKFT3TOF.cxx new file mode 100644 index 0000000000000..2579f05cc9fa9 --- /dev/null +++ b/Detectors/GenericTracking/study/tools/trackBenchTRKFT3TOF.cxx @@ -0,0 +1,20 @@ +// Copyright 2019-2020 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 trackBenchTRKFT3TOF.cxx +/// \brief The bench's run of TRKFT3TOF, the TRK with its TOF layers, in a unit of its own. + +#include "TrackBench.h" + +namespace o2::gtrk::study +{ +template int track(const Options& options); +} // namespace o2::gtrk::study diff --git a/Detectors/GenericTracking/tools/src/buildMatLUT.cxx b/Detectors/GenericTracking/tools/src/buildMatLUT.cxx index 44c998b01c235..0b49a01dc22f6 100644 --- a/Detectors/GenericTracking/tools/src/buildMatLUT.cxx +++ b/Detectors/GenericTracking/tools/src/buildMatLUT.cxx @@ -120,7 +120,7 @@ inline constexpr float kTrkRMax = 83.F; ///< beyond the OT's carbon support, and inline constexpr float kTrkGapDr = 1.F; ///< the widest band in a gap /// The bands of the barrel's layers, \a envelopes with their stacks; the discs' follow none. -std::vector trkLayers(std::span envelopes, const o2::gtrk::tools::SideWalls& walls, std::span faces, std::span chipThickness) +std::vector trkLayers(std::span envelopes, const o2::gtrk::tools::SideWalls& walls, std::span faces, std::span chipThickness, float rMaxCM, float zMaxCM) { std::vector layers; const auto cell = [&](float inner, float outer, float drPhi) { @@ -134,7 +134,7 @@ std::vector trkLayers(std::span envelop for (int band = 0; band < bands; ++band) { const float low = band == 0 ? inner : inner + ((outer - inner) * static_cast(band) / static_cast(bands)); const float high = band + 1 == bands ? outer : inner + ((outer - inner) * static_cast(band + 1) / static_cast(bands)); - layers.push_back({.rMin = low, .rMax = high, .zMax = kTrkZMax, .dz = 1.F, .drPhi = cell(low, high, drPhi)}); + layers.push_back({.rMin = low, .rMax = high, .zMax = zMaxCM, .dz = 1.F, .drPhi = cell(low, high, drPhi)}); } }; // a face closer than this to a band's edge makes no band of its own @@ -179,11 +179,11 @@ std::vector trkLayers(std::span envelop for (int part = 0; part < parts; ++part) { const float low = part == 0 ? rMin : rMin + ((rMax - rMin) * static_cast(part) / static_cast(parts)); const float high = part + 1 == parts ? rMax : rMin + ((rMax - rMin) * static_cast(part + 1) / static_cast(parts)); - layers.push_back({.rMin = low, .rMax = high, .zMax = kTrkZMax, .dz = 1.F, .drPhi = cell(low, high, drPhi)}); + layers.push_back({.rMin = low, .rMax = high, .zMax = zMaxCM, .dz = 1.F, .drPhi = cell(low, high, drPhi)}); } previous = rMax; } - addGap(previous, kTrkRMax, 0.5F); + addGap(previous, rMaxCM, 0.5F); return layers; } @@ -264,7 +264,7 @@ void populate(o2::base::MatLayerCylSet& lut, int trials, int threads) /// The TRK's bands from the loaded geometry, its stacks, side walls and /// cylinder faces printed (the LUT's provenance in its log). -std::vector trkBands(int threads) +std::vector trkBands(int threads, float rMaxCM, float zMaxCM) { using TRKFT3 = o2::gtrk::detectors::TRKFT3; const o2::gtrk::Geometry geometry(o2::gtrk::alice::placeChecked()); @@ -279,7 +279,7 @@ std::vector trkBands(int threads) std::cout << '\n'; const auto walls = o2::gtrk::tools::trkSideWalls(); std::cout << "VD side walls: " << walls.thickness * 1e4 << " um thick, r " << walls.rMin << " .. " << walls.rMax << " cm\n"; - const auto faces = o2::gtrk::tools::beamLineCylinderFaces(kTrkRMax, kTrkZMax, 1., threads); + const auto faces = o2::gtrk::tools::beamLineCylinderFaces(rMaxCM, zMaxCM, 1., threads); std::cout << "cylinder faces around the beam line [cm]:"; for (const double face : faces) { std::cout << ' ' << face; @@ -290,7 +290,7 @@ std::vector trkBands(int threads) const auto l = static_cast(layer); chipThickness.push_back((2. * specs[l].halfThickness) + stack[l].inner + stack[l].outer); } - return trkLayers(std::span{chips}.first(static_cast(kBarrel)), walls, faces, chipThickness); + return trkLayers(std::span{chips}.first(static_cast(kBarrel)), walls, faces, chipThickness, rMaxCM, zMaxCM); } /// The ITS's region, from the loaded geometry: the layers' silicon hulls @@ -408,6 +408,8 @@ int run(int argc, char** argv) std::string output; std::string geometryFile; std::string detector; + float trkRMaxCM = kTrkRMax; + float trkZMaxCM = kTrkZMax; int trials = 10; int threads = -1; float maxRelativeDifference = 0.05F; @@ -423,6 +425,10 @@ int run(int argc, char** argv) "an o2sim geometry file (o2sim_geometry-aligned.root)") // ("threads,j", bpo::value(&threads)->default_value(-1), // "fill threads; negative uses NTHREADS_MATBUD") // + ("trk-rmax-cm", bpo::value(&trkRMaxCM)->default_value(kTrkRMax), // + "TRKFT3's radial coverage [cm]; 95 reaches past the outer TOF") // + ("trk-zmax-cm", bpo::value(&trkZMaxCM)->default_value(kTrkZMax), // + "TRKFT3's longitudinal coverage [cm]; 350 reaches the TOF's acceptance") // ("max-relative-difference", bpo::value(&maxRelativeDifference)->default_value(0.05F), // "maximum relative difference when merging adjacent phi slices"); @@ -444,6 +450,9 @@ int run(int argc, char** argv) << opts << '\n'; return 1; } + if (!std::isfinite(trkRMaxCM) || !std::isfinite(trkZMaxCM) || trkRMaxCM < kTrkRMax || trkZMaxCM < kTrkZMax) { + throw std::invalid_argument("TRKFT3 material coverage can only extend the default tracker region"); + } threads = o2::gtrk::tools::fillThreads(threads); o2::base::GeometryManager::loadGeometry(geometryFile); @@ -458,9 +467,9 @@ int run(int argc, char** argv) layers = kMftLayers; radialCheck = 20.F; } else { - bands = trkBands(threads); + bands = trkBands(threads, trkRMaxCM, trkZMaxCM); layers = bands; - radialCheck = kTrkRMax; + radialCheck = trkRMaxCM; } o2::base::MatLayerCylSet lut; diff --git a/Detectors/GenericTracking/tools/src/layerLinks.cxx b/Detectors/GenericTracking/tools/src/layerLinks.cxx index 35730e5442b80..6700e017148b6 100644 --- a/Detectors/GenericTracking/tools/src/layerLinks.cxx +++ b/Detectors/GenericTracking/tools/src/layerLinks.cxx @@ -42,6 +42,7 @@ #include "GenericTracking/Detectors/ITS.h" #include "GenericTracking/Detectors/MFT.h" #include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" #include "GenericTracking/Alice/Placement.h" #include "GenericTracking/Tracking/SearchWindow.h" #include "GenericTracking/WorkflowTRK/TRK.h" @@ -439,7 +440,7 @@ int run(int argc, char** argv) bpo::options_description description("Trace a detector's layer links"); description.add_options() // ("help,h", "this message") // - ("detector,d", bpo::value(&options.detector)->required(), "ITS, MFT or TRKFT3") // + ("detector,d", bpo::value(&options.detector)->required(), "ITS, MFT, TRKFT3 or TRKFT3TOF") // ("beam-spot-z", bpo::value(&options.beamSpotZ)->default_value(0.), "centre of the traced vertex range [cm]") // ("beam-spot-range", bpo::value(&options.beamSpotHalfRange)->default_value(18.), "half-width of the traced vertex range [cm]; 3 sigma of a 6 cm spot by default") // @@ -476,7 +477,7 @@ int run(int argc, char** argv) } // The field as the tracking takes it: O2's nominal Bz of the run's map; // for ALICE 3, whose GRP records none, its field object's Bz at the origin. - if (options.detector == "TRKFT3") { + if (options.detector == "TRKFT3" || options.detector == "TRKFT3TOF") { options.bzKiloGauss = alice::alice3BzKiloGauss(); } else { if (options.field.empty()) { @@ -498,6 +499,9 @@ int run(int argc, char** argv) if (options.detector == "TRKFT3") { return runFor(options); } + if (options.detector == "TRKFT3TOF") { + return runFor(options); + } std::cerr << "unknown detector '" << options.detector << "'\n"; return 1; } diff --git a/Detectors/GenericTracking/tracking/GPU/CMakeLists.txt b/Detectors/GenericTracking/tracking/GPU/CMakeLists.txt index 43b3564fbd222..f25aae73bbccd 100644 --- a/Detectors/GenericTracking/tracking/GPU/CMakeLists.txt +++ b/Detectors/GenericTracking/tracking/GPU/CMakeLists.txt @@ -103,7 +103,7 @@ foreach(backend IN ITEMS CUDA HIP) string(LENGTH ${lower} lower_length) # One device tracker per layout and unit, compiled in parallel. - gtrk_device_library(GTrkTracking${backend} ${backend} cuda/DeviceRuntime.cu cuda/DeviceTrackerITS.cu cuda/DeviceTrackerMFT.cu cuda/DeviceTrackerTRKFT3.cu cuda/DeviceDecayFitterTRKFT3.cu) + gtrk_device_library(GTrkTracking${backend} ${backend} cuda/DeviceRuntime.cu cuda/DeviceTrackerITS.cu cuda/DeviceTrackerMFT.cu cuda/DeviceTrackerTRKFT3.cu cuda/DeviceTrackerTRKFT3TOF.cu cuda/DeviceDecayFitterTRKFT3.cu) set(target ${GTrkTracking${backend}_TARGET}) target_link_libraries(${target} PUBLIC O2::GTrkTracking) # Register caps of the CUDA units. Under relocatable device code a kernel's @@ -118,7 +118,7 @@ foreach(backend IN ITEMS CUDA HIP) # none: there the follow already runs at the register file's limit, and a # lower one only spills. if(backend STREQUAL "CUDA" AND NOT GPUCA_DETERMINISTIC_MODE GREATER_EQUAL ${GPUCA_DETERMINISTIC_MODE_MAP_NO_FAST_MATH}) - set_source_files_properties(cuda/DeviceTrackerITS.cu cuda/DeviceTrackerTRKFT3.cu PROPERTIES COMPILE_OPTIONS -maxrregcount=96) + set_source_files_properties(cuda/DeviceTrackerITS.cu cuda/DeviceTrackerTRKFT3.cu cuda/DeviceTrackerTRKFT3TOF.cu PROPERTIES COMPILE_OPTIONS -maxrregcount=96) set_source_files_properties(cuda/DeviceTrackerMFT.cu PROPERTIES COMPILE_OPTIONS -maxrregcount=128) endif() gtrk_device_target(${target} ${backend} SHARED "_ZN2o24gtrk3gpu${lower_length}${lower}11makeRuntimeEi") diff --git a/Detectors/GenericTracking/tracking/GPU/cuda/DeviceRuntime.cu b/Detectors/GenericTracking/tracking/GPU/cuda/DeviceRuntime.cu index 54d0bac76504c..c0c7d8e6d380c 100644 --- a/Detectors/GenericTracking/tracking/GPU/cuda/DeviceRuntime.cu +++ b/Detectors/GenericTracking/tracking/GPU/cuda/DeviceRuntime.cu @@ -43,6 +43,7 @@ namespace o2::gtrk::gpu::GTRK_BACKEND_NAMESPACE std::unique_ptr> makeITSTracker(DeviceRuntime& runtime, DeviceBlock block); std::unique_ptr> makeMFTTracker(DeviceRuntime& runtime, DeviceBlock block); std::unique_ptr> makeTRKFT3Tracker(DeviceRuntime& runtime, DeviceBlock block); +std::unique_ptr> makeTRKFT3TOFTracker(DeviceRuntime& runtime, DeviceBlock block); std::unique_ptr> makeTRKFT3DecayFitter(DeviceRuntime& runtime, DeviceBlock block); namespace @@ -208,6 +209,7 @@ class Runtime final : public DeviceRuntime [[nodiscard]] std::unique_ptr> makeITSTracker(DeviceBlock block) final { return GTRK_BACKEND_NAMESPACE::makeITSTracker(*this, block); } [[nodiscard]] std::unique_ptr> makeMFTTracker(DeviceBlock block) final { return GTRK_BACKEND_NAMESPACE::makeMFTTracker(*this, block); } [[nodiscard]] std::unique_ptr> makeTRKFT3Tracker(DeviceBlock block) final { return GTRK_BACKEND_NAMESPACE::makeTRKFT3Tracker(*this, block); } + [[nodiscard]] std::unique_ptr> makeTRKFT3TOFTracker(DeviceBlock block) final { return GTRK_BACKEND_NAMESPACE::makeTRKFT3TOFTracker(*this, block); } [[nodiscard]] std::unique_ptr> makeTRKFT3DecayFitter(DeviceBlock block) final { return GTRK_BACKEND_NAMESPACE::makeTRKFT3DecayFitter(*this, block); } DeviceProperties mProperties; diff --git a/Detectors/GenericTracking/tracking/GPU/cuda/DeviceTrackerTRKFT3TOF.cu b/Detectors/GenericTracking/tracking/GPU/cuda/DeviceTrackerTRKFT3TOF.cu new file mode 100644 index 0000000000000..76fb75257a3ea --- /dev/null +++ b/Detectors/GenericTracking/tracking/GPU/cuda/DeviceTrackerTRKFT3TOF.cu @@ -0,0 +1,31 @@ +// Copyright 2019-2020 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 DeviceTrackerTRKFT3TOF.cu +/// \brief The backend's device tracker for ALICE 3's TRKFT3TOF, the TRK with its TOF layers. +/// One translation unit per layout, so +/// that the layouts compile in parallel. + +#include "DeviceTracker.cuh" + +#include "GenericTracking/Detectors/TRKFT3TOF.h" + +#include "DetectorsBase/MatLayerCylSet.h" + +#include +#include + +namespace o2::gtrk::gpu::GTRK_BACKEND_NAMESPACE +{ + +std::unique_ptr> makeTRKFT3TOFTracker(DeviceRuntime& runtime, DeviceBlock block) { return std::make_unique>(runtime, block); } + +} // namespace o2::gtrk::gpu::GTRK_BACKEND_NAMESPACE diff --git a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/Follow.h b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/Follow.h index 6e33f1f2267e5..9487564544b5a 100644 --- a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/Follow.h +++ b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/Follow.h @@ -310,6 +310,11 @@ struct FollowProposal { std::uint32_t outward[K]{}; std::uint32_t inward[K]{}; std::uint32_t replacedEnd = std::numeric_limits::max(); + /// A row on an inactive layer between two of the track's rows (LayerSpec.h), + /// inserted before its row `interiorAt` (`FollowStage::interior`); none + /// without. + std::uint32_t interior = std::numeric_limits::max(); + std::uint8_t interiorAt = 0U; std::uint8_t outwardCount = 0U; std::uint8_t inwardCount = 0U; }; @@ -869,6 +874,22 @@ struct NoBeamEndHistory { template using BeamEndHistoryOf = std::conditional_t; +/// \a rows with \a row inserted before their \a at-th, as the fit reads a +/// chain: a track with its interior row (`FollowStage::interior`). +template +struct InsertedChain { + const TimeFrame* frame = nullptr; + const std::uint32_t* rows = nullptr; + std::uint32_t at = 0U; + std::uint32_t row = 0U; + + [[nodiscard]] GPUhdi() GPUAlwaysInline() Measurement operator[](int i) const + { + const auto k = static_cast(i); + return measurementAt(*frame, k < at ? rows[k] : (k == at ? row : rows[k - 1U])); + } +}; + /// A layer a step may reach: its nominal crossing and its distance from the /// track, squared. struct Target { @@ -1018,8 +1039,14 @@ class FollowStage return; } } - const std::uint32_t capacity = static_cast(kMaxClusters) - count; + std::uint32_t capacity = static_cast(kMaxClusters) - count; auto box = trackTimeBox(mFrame->measurements(), rows, static_cast(count)); + // A row on an inactive layer the track's road straddles (`interior`). + if constexpr (Detector::inactiveLayers != 0U) { + if (capacity > 1U && interior(outer, rows, count, box, proposal)) { + --capacity; + } + } proposal.outwardCount = walk(outer, PropagationDirection::kForward, proposal.outward, capacity, box, observe, std::numeric_limits::max(), group); walkInward(inner, rows.index[0], capacity - proposal.outwardCount, box, proposal, observe, group); } @@ -1145,6 +1172,11 @@ class FollowStage // Whether the latest step saw a row near where it took none (the unconfirmed drop, below). bool nearMiss = false; [[maybe_unused]] follow::BeamEndHistoryOf history; // NOLINT(misc-const-correctness): written in a dependent call the check does not see + // The inactive layers' tail resumes from the state and time box before + // the last row when the unconfirmed drop removes it. + [[maybe_unused]] BoundParameters beforeLast = branch.state; + [[maybe_unused]] CovarianceFactors beforeLastFactors = branch.factors; + [[maybe_unused]] TimeEstPS beforeLastBox = box; while (branch.count < capacity) { const LayerID current = mGeometry->surface(branch.state.surface).layer; observe.step(current, branch.state, branch.factors, branch.count); @@ -1164,6 +1196,11 @@ class FollowStage history.remember(branch.state, branch.factors); } } + if constexpr (Detector::inactiveLayers != 0U) { + beforeLast = branch.state; + beforeLastFactors = branch.factors; + beforeLastBox = box; + } take(branch, box, child); continue; } @@ -1181,8 +1218,10 @@ class FollowStage const bool evidence = (direction == PropagationDirection::kBackward && nearMiss) || branch.lastChi2 < mParameters->followKeepChi2; // With EndDensity also an // outward last row of a high density stays (`densityKept`). + [[maybe_unused]] bool dropped = false; if (branch.crossed && !evidence && branch.count != 0U && !densityKept(branch, direction)) { --branch.count; + dropped = true; countWork(WorkCounter::kFollowUnconfirmed); observe.unconfirmed(branch.rows[branch.count]); } @@ -1205,6 +1244,30 @@ class FollowStage observe.refusedBeamEnd(branch.rows[branch.count]); } } + if constexpr (Detector::inactiveLayers != 0U) { + // The inactive layers' tail: outward, where the walk ended before them + // -- a hole, no row, or no link on -- one nominal step after another + // from its last state onto the inactive layers it has no row on, + // nearest crossing first (`inactiveLayerTail`), until a step takes none. + // Where the unconfirmed drop removed the last row, from the state + // before that row. + if (dropped) { + branch.state = beforeLast; + branch.factors = beforeLastFactors; + box = beforeLastBox; + } + if (direction == PropagationDirection::kForward && end != FollowEnd::kCapacity) { + while (branch.count < capacity) { + Child child; + bool nearTail = false; + if (!inactiveLayerTail(branch, box, direction, child, nearTail, observe, group)) { + break; + } + observe.taken(child.row, child.chi2); + take(branch, box, child); + } + } + } observe.end(end); for (std::uint32_t i = 0; i < branch.count; ++i) { rows[i] = branch.rows[i]; @@ -1395,6 +1458,161 @@ class FollowStage return false; } + /// The interior row: the first inactive layer between two + /// consecutive rows of the track, \a rows' i and i + 1 -- a link from the + /// first's layer onto it, and one from it onto the second's -- which a road + /// crosses without a row on it, the follow never visiting it. From the + /// track's forward pass cut at row i (its first i + 1 rows, at least + /// three), or else its inward pass from \a outer, its outward state, cut at + /// row i + 1 (at least three rows), a nominal step onto it, with the + /// track's time \a box: of the + /// free rows it passes (the four best), the one whose insertion raises the + /// track's fit chi2 least, under the layer's gate, goes into \a proposal + /// before row i + 1 and narrows \a box. Whether one did. + [[nodiscard]] GPUhdi() bool interior(const BoundTrackState& outer, const ClusterList& rows, std::uint32_t count, TimeEstPS& box, Proposal& proposal) const + { + const auto& measurements = mFrame->measurements(); + const auto linked = [&](LayerID from, LayerID to) { + for (auto at = mParameters->allOutLinkOffsets[from]; at < mParameters->allOutLinkOffsets[from + 1U]; ++at) { + if (mParameters->linkTargets[mParameters->allOutLinkIndices[at]] == to) { + return true; + } + } + return false; + }; + for (std::uint32_t i = 0U; i + 1U < count; ++i) { + const LayerID before = mGeometry->surface(measurements.surface[rows.index[i]]).layer; + const LayerID after = mGeometry->surface(measurements.surface[rows.index[i + 1U]]).layer; + for (std::uint64_t left = Detector::inactiveLayers; left != 0U; left &= left - 1U) { + const auto layer = static_cast(o2::gpu::CAMath::Ctz64(left)); + if (layer == before || layer == after || !linked(before, layer) || !linked(layer, after)) { + continue; + } + const bool forward = i + 1U >= 3U; + if (!forward && count - i - 1U < 3U) { + return false; + } + const auto direction = forward ? PropagationDirection::kForward : PropagationDirection::kBackward; + const RowChain chain{.frame = mFrame, .rows = rows.index}; + BoundTrackState state; + Scalar chi2 = 0.F; + std::int16_t failed = -1; + std::int16_t kinkAt = -1; + int kinks = 0; + // A pass takes its start's values alone (`runPass`): the whole + // chain's helix forward, the outward state inward. + const BoundTrackState start = forward ? makeChainSeed(mPropagator, *mGeometry, chain, static_cast(count)) : outer; + const RowChain side{.frame = mFrame, .rows = forward ? rows.index : rows.index + i + 1U}; + const auto sideCount = static_cast(forward ? i + 1U : count - i - 1U); + const auto span = detail::spanMaterial(*mGeometry, *mMaterial, side, sideCount); + if (detail::runPass(mPropagator, *mGeometry, span, side, sideCount, direction, start, state, chi2, failed, KinkBudget{}, kinks, kinkAt, NoFitObserver{}) != PropagationStatus::kOk) { + return false; + } + const auto prediction = predictLayerCrossing(mPropagator, *mParameters, mGeometry->planeOf(state), state, layer, direction); + if (prediction.status != PropagationStatus::kOk) { + return false; + } + const follow::Target target{.distance2 = 0.F, .layer = layer, .prediction = prediction}; + const auto factors = factorCovariance(state.cov); + CandidateWindow window; + Scalar reach[2]{}; + detail::StepMaterial traversed; + if (!targetWindow(state, factors, box, target, direction, window, reach, traversed, SoloGroup{})) { + return false; + } + constexpr std::uint32_t kKept = 4U; + std::uint32_t candidates[kKept]; + Scalar chi2s[kKept]; + std::uint32_t n = 0U; + follow::visitInline( + context(), state, factors, 0.F, 0.F, layer, direction, window, traversed, 0U, WorkCounter::kFollowUpdates, SoloGroup{}, [](std::uint32_t /*row*/, StepOutcome /*outcome*/, Scalar /*chi2*/) {}, + [&](const auto& candidate) { + std::uint32_t slot = n < kKept ? n++ : kKept; + if (slot == kKept && !(candidate.chi2 < chi2s[kKept - 1U])) { + return; + } + slot = slot == kKept ? kKept - 1U : slot; + while (slot > 0U && candidate.chi2 < chi2s[slot - 1U]) { + candidates[slot] = candidates[slot - 1U]; + chi2s[slot] = chi2s[slot - 1U]; + --slot; + } + candidates[slot] = candidate.row; + chi2s[slot] = candidate.chi2; + }); + if (n == 0U) { + return false; + } + const auto budget = kinkBudget(*mParameters); + const auto plain = fitMeasurements(mPropagator, *mGeometry, *mMaterial, chain, static_cast(count), budget); + if (plain.status != PropagationStatus::kOk) { + return false; + } + std::uint32_t best = ClusterList::kNoCluster; + Scalar bestDelta = mParameters->clusterChi2Max; + for (std::uint32_t c = 0; c < n; ++c) { + const follow::InsertedChain with{.frame = mFrame, .rows = rows.index, .at = i + 1U, .row = candidates[c]}; + const auto fit = fitMeasurements(mPropagator, *mGeometry, *mMaterial, with, static_cast(count + 1U), budget); + if (fit.status == PropagationStatus::kOk && fit.chi2 - plain.chi2 <= bestDelta) { + bestDelta = fit.chi2 - plain.chi2; + best = candidates[c]; + } + } + if (best == ClusterList::kNoCluster) { + return false; + } + proposal.interior = best; + proposal.interiorAt = static_cast(i + 1U); + box += timeBoxAt(measurements, best); + return true; + } + } + return false; + } + + /// The inactive layers' tail of \a branch's walk (\a Det's + /// `inactiveLayers`): the inactive layers it holds no row on and its state + /// crosses ahead, nearest first, searched as a nominal step is + /// (`nominal`), the holes not counted. Whether it found a row, into \a child. + template + [[nodiscard]] GPUhdi() bool inactiveLayerTail(Branch& branch, const TimeEstPS& box, PropagationDirection direction, Child& child, bool& nearMiss, const Observer& observe, const Group& group) const + { + follow::Target targets[follow::maxDegree]; + std::uint32_t nTargets = 0U; + const auto& from = mGeometry->planeOf(branch.state); + Scalar here[3]{}; + surfaceToGlobal(from, branch.state.loc0(), branch.state.loc1(), here); + for (std::uint64_t left = Detector::inactiveLayers; left != 0U && nTargets < follow::maxDegree; left &= left - 1U) { + const auto layer = static_cast(o2::gpu::CAMath::Ctz64(left)); + bool held = mGeometry->surface(branch.state.surface).layer == layer; + for (std::uint32_t i = 0; i < branch.count; ++i) { + held = held || mGeometry->surface(mFrame->measurements().surface[branch.rows[i]]).layer == layer; + } + if (held) { + continue; + } + const auto prediction = predictLayerCrossing(mPropagator, *mParameters, from, branch.state, layer, direction); + if (prediction.status != PropagationStatus::kOk) { + continue; + } + Scalar point[3]{}; + follow::crossingPoint(*mParameters, layer, prediction, point); + const Scalar d2 = ((point[0] - here[0]) * (point[0] - here[0])) + ((point[1] - here[1]) * (point[1] - here[1])) + ((point[2] - here[2]) * (point[2] - here[2])); + std::uint32_t slot = nTargets++; + while (slot > 0U && d2 < targets[slot - 1U].distance2) { + targets[slot] = targets[slot - 1U]; + --slot; + } + targets[slot] = {.distance2 = d2, .layer = layer, .prediction = prediction}; + } + if (nTargets == 0U) { + return false; + } + Branch tail = branch; + tail.holes = 0U; + return nominal(tail, box, direction, targets, nTargets, child, nearMiss, observe, group); + } + /// The nominal pass of a step of \a branch over its \a nTargets /// \a targets (`overTargets`): the first target with a row in the gate /// gives \a child -- the row, or, with more than one, the lookahead's best confirmed @@ -1565,6 +1783,12 @@ class FollowStage /// crossing's angle. [[nodiscard]] GPUhdi() GPUAlwaysInline() bool crossesSensor(const BoundParameters& state, const follow::Target& target, const Scalar* reach, PropagationDirection direction) const { + // An inactive layer is never a hole, nor a crossing the unconfirmed drop reads (LayerSpec.h). + if constexpr (Detector::inactiveLayers != 0U) { + if (Detector::isInactiveLayer(target.layer)) { + return false; + } + } countWork(WorkCounter::kFollowHoleTests); const auto& from = mGeometry->planeOf(state); Scalar point[3]{}; @@ -1675,6 +1899,9 @@ struct Bid { for (std::uint32_t i = 0; i < proposal.inwardCount; ++i) { o2::gpu::CAMath::AtomicMax(slots + proposal.inward[i], priority); } + if (proposal.interior != ClusterList::kNoCluster) { + o2::gpu::CAMath::AtomicMax(slots + proposal.interior, priority); + } } }; @@ -1697,6 +1924,9 @@ struct Resolve { const std::uint32_t proposed = static_cast(proposal.outwardCount) + proposal.inwardCount; proposal.outwardCount = kept(proposal.outward, proposal.outwardCount, priority); proposal.inwardCount = kept(proposal.inward, proposal.inwardCount, priority); + if (proposal.interior != ClusterList::kNoCluster && slots[proposal.interior] != priority) { + proposal.interior = ClusterList::kNoCluster; + } countWork(earlier ? WorkCounter::kFollowEarlierProposed : WorkCounter::kFollowProposed, proposed); countWork(earlier ? WorkCounter::kFollowEarlierOutbid : WorkCounter::kFollowOutbid, proposed - proposal.outwardCount - proposal.inwardCount); } @@ -1735,10 +1965,19 @@ struct Combine { } // A replaced end goes with the outward rows that replace it. const bool replaced = proposal.replacedEnd != ClusterList::kNoCluster && proposal.outwardCount != 0U; - const std::uint32_t kept = originalCount[track] - (replaced ? 1U : 0U); - for (std::uint32_t i = 0; i < kept; ++i) { - combined.index[static_cast(proposal.inwardCount) + i] = original[track].index[i]; + std::uint32_t kept = originalCount[track] - (replaced ? 1U : 0U); + // An interior row goes before the track's row it was found before. + const bool interior = proposal.interior != ClusterList::kNoCluster; + for (std::uint32_t i = 0, at = proposal.inwardCount; i < kept; ++i) { + if (interior && i == proposal.interiorAt) { + combined.index[at++] = proposal.interior; + } + combined.index[at++] = original[track].index[i]; + } + if (interior && proposal.interiorAt >= kept) { + combined.index[static_cast(proposal.inwardCount) + kept] = proposal.interior; } + kept += interior ? 1U : 0U; for (std::uint32_t i = 0; i < proposal.outwardCount; ++i) { combined.index[static_cast(proposal.inwardCount) + kept + i] = proposal.outward[i]; } @@ -1782,7 +2021,7 @@ struct Refit { { const std::uint32_t track = trackOffset + element; auto& proposal = proposals[element]; - const std::uint32_t added = static_cast(proposal.outwardCount) + proposal.inwardCount; + const std::uint32_t added = static_cast(proposal.outwardCount) + proposal.inwardCount + (proposal.interior != ClusterList::kNoCluster ? 1U : 0U); if (added == 0U) { return; } @@ -1796,6 +2035,7 @@ struct Refit { countWork(earlier ? WorkCounter::kFollowEarlierRefitRejected : WorkCounter::kFollowRefitRejected, added); proposal.outwardCount = 0U; proposal.inwardCount = 0U; + proposal.interior = ClusterList::kNoCluster; } } @@ -1894,6 +2134,12 @@ struct TrimAmbiguous { // The outward rows are the track's last (`Combine`). ClusterList rows = tracks.clusters[track]; const std::uint32_t row = rows.index[count - 1U]; + // Preserve the last row when it comes from an inactive layer. + if constexpr (Detector::inactiveLayers != 0U) { + if (Detector::isInactiveLayer(geometry->surface(frame->measurements().surface[row]).layer)) { + return; + } + } rows.index[count - 1U] = ClusterList::kNoCluster; const auto shorter = static_cast(count - 1U); countWork(WorkCounter::kFollowTrimFits); @@ -1933,6 +2179,9 @@ struct Mark { for (std::uint32_t i = 0; i < proposal.inwardCount; ++i) { used[proposal.inward[i]] = kExclusive; } + if (proposal.interior != ClusterList::kNoCluster) { + used[proposal.interior] = kExclusive; + } } }; diff --git a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/GPU/DeviceRuntime.h b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/GPU/DeviceRuntime.h index d558f1d1ec007..affb9f1daf5ea 100644 --- a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/GPU/DeviceRuntime.h +++ b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/GPU/DeviceRuntime.h @@ -24,6 +24,7 @@ #include "GenericTracking/Detectors/ITS.h" #include "GenericTracking/Detectors/MFT.h" #include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" #include "GenericTracking/Tracking/GPU/DeviceArena.h" #include "GenericTracking/Tracking/GPU/DeviceStream.h" @@ -111,6 +112,8 @@ class DeviceRuntime return makeMFTTracker(block); } else if constexpr (std::is_same_v) { return makeTRKFT3Tracker(block); + } else if constexpr (std::is_same_v) { + return makeTRKFT3TOFTracker(block); } else { throw std::runtime_error(std::string{"GPU backend "} + backend() + ": no device tracker is built for " + D::name); } @@ -141,6 +144,7 @@ class DeviceRuntime [[nodiscard]] virtual std::unique_ptr> makeITSTracker(DeviceBlock block) = 0; [[nodiscard]] virtual std::unique_ptr> makeMFTTracker(DeviceBlock block) = 0; [[nodiscard]] virtual std::unique_ptr> makeTRKFT3Tracker(DeviceBlock block) = 0; + [[nodiscard]] virtual std::unique_ptr> makeTRKFT3TOFTracker(DeviceBlock block) = 0; [[nodiscard]] virtual std::unique_ptr> makeTRKFT3DecayFitter(DeviceBlock block) = 0; }; diff --git a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/Iteration.h b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/Iteration.h index 94d0cc8b0083d..567c573741b3e 100644 --- a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/Iteration.h +++ b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/Iteration.h @@ -85,8 +85,8 @@ struct IterationSettings { /// no link that skips a layer (`LayerLink::skipsLayer`) and on the others no pair /// that crosses one, so a track beyond a shorter layer's end is still made. bool skipLinks = true; - /// The layers this iteration's links join, a bit per layer; 0 for every - /// layer. A link is taken only when both its layers are in the mask: the + /// The layers this iteration's links join, a bit per layer; 0 for the + /// layout's default (every layer unless the layout sets a default mask). A link is taken only when both its layers are in the mask: the /// vertexing pass takes the three innermost. std::uint64_t layerMask = 0U; /// The layers a road may end on, a bit per layer; 0 for any. With a mask a @@ -104,7 +104,7 @@ struct IterationSettings { /// count; 0 for none. O2's ITS `TrackingParameters::MinPt`, by track /// length. The final track's: where the iteration /// follows, after the follow, on the track's count then; else on the road. - static constexpr std::size_t kClusterSlots = 16U; + static constexpr std::size_t kClusterSlots = 18U; std::array minPtGeVByClusters{}; /// How many of a track's innermost clusters this iteration's selection and /// follow let it share; 0, strict: the @@ -445,7 +445,13 @@ template template [[nodiscard]] inline std::array> takenLinks(const IterationSettings& settings) { - const auto inMask = [&](LayerID layer) { return settings.layerMask == 0U || ((settings.layerMask >> layer) & 1U) != 0U; }; + auto mask = settings.layerMask; + if constexpr (requires { Det::defaultSeedingMask; }) { + if (mask == 0U) { + mask = Det::defaultSeedingMask; + } + } + const auto inMask = [&](LayerID layer) { return mask == 0U || ((mask >> layer) & 1U) != 0U; }; std::array> allowed{}; for (std::size_t link = 0; link < nLinks; ++link) { const auto& pair = Det::layerLinks[link]; diff --git a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/LayerMaterial.h b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/LayerMaterial.h index bb0aaadcff602..d9fae48e78bee 100644 --- a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/LayerMaterial.h +++ b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/LayerMaterial.h @@ -193,7 +193,12 @@ template // The half-gaps to the neighbours of the same kind and, for discs, side. const auto neighbour = [&](int step) -> double { - const auto other = static_cast(layer) + step; + auto other = static_cast(layer) + step; + // A layer's slab reaches past an inactive neighbour (LayerSpec.h), as + // in the layout without it: its material stays where it was. + while (!Detector::isInactiveLayer(id) && other >= 0 && std::cmp_less(other, kLayers) && Detector::isInactiveLayer(static_cast(other))) { + other += step; + } if (other < 0 || std::cmp_greater_equal(other, kLayers)) { return 0.; } diff --git a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/LinkHoles.h b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/LinkHoles.h index cf7759a214bec..d31f60282c6f3 100644 --- a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/LinkHoles.h +++ b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/LinkHoles.h @@ -202,7 +202,8 @@ template std::uint64_t holes = 0U; for (int layer = 0; layer < Detector::nLayers; ++layer) { const auto id = static_cast(layer); - if (id == from || id == to) { + // An inactive layer leaves no hole (LayerSpec.h). + if (id == from || id == to || Detector::isInactiveLayer(id)) { continue; } const bool barrel = Detector::isBarrelLayer(id); diff --git a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/SlicePlan.h b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/SlicePlan.h index fc217e22f7e93..1a0b09c7b779f 100644 --- a/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/SlicePlan.h +++ b/Detectors/GenericTracking/tracking/include/GenericTracking/Tracking/SlicePlan.h @@ -151,9 +151,10 @@ struct SliceReach { [[nodiscard]] std::int64_t haloPS() const { return gatePS() + std::max(pairForwardPS, pairBackwardPS); } }; -/// The reach of a frame whose rows have \a bounds, on \a geometry's frames. +/// The reach of a frame whose rows have \a bounds, on \a geometry's frames, +/// along the links \a taken marks, or every link without it. template -[[nodiscard]] SliceReach sliceReach(const HaloBounds& bounds, const GridGeometry& geometry) +[[nodiscard]] SliceReach sliceReach(const HaloBounds& bounds, const GridGeometry& geometry, const std::array>* taken = nullptr) { const auto sameFrames = [&](const LayerLink& link) { const auto& frames = geometry.frames(link.from); @@ -166,6 +167,9 @@ template result.forwardPS = std::max(result.forwardPS, forwardTo[layer]); result.backwardPS = std::max(result.backwardPS, backwardTo[layer]); for (auto i = outLinks.begin(layer); i < outLinks.end(layer); ++i) { + if (taken != nullptr && !(*taken)[outLinks.links[i]]) { + continue; + } const auto& link = Det::layerLinks[outLinks.links[i]]; const bool zero = sameFrames(link); const std::int64_t forward = zero ? 0 : bounds.widthPS[link.from]; @@ -179,6 +183,134 @@ template return result; } +/// The reach of the chains one iteration builds on the links \a taken marks, +/// with the triplets' time cut: in a chain `m0 m1 ... mk` of measurements on +/// consecutive links, every pair `m(i) m(i+1)` overlaps (the tracklet) and so +/// does every `m(i) m(i+2)` (`tripletTimeCompatible`, the triplet's first and +/// third). So `m(i+2)` reaches `m(i)` as a pair on the layers two links +/// apart, 0 both ways when those two share frames and their rows are them, +/// whatever the layer between -- a narrow box, a TOF hit's, between two +/// layers of the same frames moves neither. +/// +/// Each bound is a sum of link and two-link reaches along the chain. For a +/// chain ending `x -> a -> b`, `b` drifts from `m0` by at most the bound at `a` +/// plus the link's reach and at most the bound at `x` plus the two-link +/// reach: the lesser of the two. Per link, the largest such bound over the +/// chains ending on it (`forwardTo`), and per layer over the chains ending +/// there (`forwardAt`); upper bounds of the same terms, so the lesser of +/// them bounds every chain (by induction along `layerOrder`). `R+` and `R-` +/// are the largest over the links, the forward and the backward bound alike; +/// the pair reaches are the links' own, as in `sliceReach`. A chain of two +/// measurements alone -- a tracklet no triplet takes -- is on no road and in +/// no level (a road holds a triplet), so a chain's first link counts in `R+` +/// and `R-` only where a taken link goes on from its target; it always counts +/// in the pair reaches, which size the halo's edge. Never more than +/// `sliceReach` along the same links. +template +[[nodiscard]] SliceReach chainReach(const HaloBounds& bounds, const GridGeometry& geometry, const std::array>& taken) +{ + constexpr auto kLayers = HaloBounds::kLayerCount; + const auto zero = [&](LayerID from, LayerID to) { + return geometry.frames(from) == geometry.frames(to) && bounds.rowsAreFrames[from] && bounds.rowsAreFrames[to]; + }; + const auto forwardOf = [&](LayerID from, LayerID to) -> std::int64_t { return zero(from, to) ? 0 : bounds.widthPS[from]; }; + const auto backwardOf = [&](LayerID from, LayerID to) -> std::int64_t { return zero(from, to) ? 0 : bounds.widthPS[to]; }; + SliceReach result; + std::array> forwardTo{}; + std::array> backwardTo{}; + std::array forwardAt{}; + std::array backwardAt{}; + for (const auto layer : layerOrder) { + // Every link into this layer is done: its source comes earlier in the order. + for (auto i = inLinks.begin(layer); i < inLinks.end(layer); ++i) { + if (taken[inLinks.links[i]]) { + forwardAt[layer] = std::max(forwardAt[layer], forwardTo[inLinks.links[i]]); + backwardAt[layer] = std::max(backwardAt[layer], backwardTo[inLinks.links[i]]); + } + } + for (auto o = outLinks.begin(layer); o < outLinks.end(layer); ++o) { + const auto out = outLinks.links[o]; + if (!taken[out]) { + continue; + } + const LayerID target = Det::layerLinks[out].to; + const std::int64_t forward = forwardOf(layer, target); + const std::int64_t backward = backwardOf(layer, target); + result.pairForwardPS = std::max(result.pairForwardPS, forward); + result.pairBackwardPS = std::max(result.pairBackwardPS, backward); + // The chains with a measurement before this layer: three or more. + std::int64_t longerForward = 0; + std::int64_t longerBackward = 0; + for (auto i = inLinks.begin(layer); i < inLinks.end(layer); ++i) { + const auto in = inLinks.links[i]; + if (!taken[in]) { + continue; + } + const LayerID before = Det::layerLinks[in].from; + longerForward = std::max(longerForward, std::min(forwardTo[in] + forward, forwardAt[before] + forwardOf(before, target))); + longerBackward = std::max(longerBackward, std::min(backwardTo[in] + backward, backwardAt[before] + backwardOf(before, target))); + } + // A chain starting on this layer is this link's pair, the bound of the + // longer chains it starts. + forwardTo[out] = std::max(forward, longerForward); + backwardTo[out] = std::max(backward, longerBackward); + // Only a chain of three or more measurements -- one with a triplet -- + // is on a road or a level: the pair alone counts where a taken link + // goes on from its target. + const bool continues = outLinks.end(target) > outLinks.begin(target) && [&] { + for (auto n = outLinks.begin(target); n < outLinks.end(target); ++n) { + if (taken[outLinks.links[n]]) { + return true; + } + } + return false; + }(); + result.forwardPS = std::max({result.forwardPS, longerForward, continues ? forward : std::int64_t{0}}); + result.backwardPS = std::max({result.backwardPS, longerBackward, continues ? backward : std::int64_t{0}}); + } + } + return result; +} + +/// The time a slice's seeding needs past its core: the gate and the halo +/// (`SliceReach::gatePS`, `haloPS`), each the largest of the iterations'. +struct SeedingReach { + std::int64_t gatePS = 0; + std::int64_t haloPS = 0; +}; + +/// The reach the seeding of \a iterations needs: each iteration's along the +/// links it takes (its out-link lists, `takenLinks`), with the triplets' time +/// cut (`chainReach`); of their gates and of their halos the largest. A +/// chain -- tracklet, triplet, neighbour, road, and the chains into a road its +/// levels count -- belongs to one iteration (an iteration on its +/// predecessor's graph, `sharedGraph`, takes the same links) and lies on its +/// taken links, every three consecutive measurements a triplet; so a link no +/// iteration takes, or a path through two iterations' links, widens no gate. +/// The gate is each iteration's `R+ + R-`, and the largest of those -- not +/// the largest `R+` plus the largest `R-`, which two iterations can make +/// without either needing it. The follow does not work in slices. With no +/// iterations, every link's pairwise (`sliceReach`). +template +[[nodiscard]] SeedingReach seedingReach(const HaloBounds& bounds, const GridGeometry& geometry, std::span> iterations) +{ + if (iterations.empty()) { + const auto every = sliceReach(bounds, geometry); + return {.gatePS = every.gatePS(), .haloPS = every.haloPS()}; + } + SeedingReach result; + for (const auto& parameters : iterations) { + std::array> taken{}; + for (auto i = parameters.outLinkOffsets[0]; i < parameters.outLinkOffsets[HaloBounds::kLayerCount]; ++i) { + taken[parameters.outLinkIndices[i]] = true; + } + const auto reach = chainReach(bounds, geometry, taken); + result.gatePS = std::max(result.gatePS, reach.gatePS()); + result.haloPS = std::max(result.haloPS, reach.haloPS()); + } + return result; +} + /// One slice of a timeframe: its blocks and rows, its tracklet sources, and /// the gate's window of box starts around its core. template @@ -277,7 +409,7 @@ struct TimeframePlan { /// \a plan with the vertex list \a vertices, sorted by time, and each /// iteration's vertex windows from it and \a windowSettings, the settings its /// parameters were derived from. The slices and the frame's bounds stay as -/// they are: they depend on the frame alone, so a plan made before the +/// they are: they depend on the frame and iterations, so a plan made before the /// vertexer's list was known is replanned with it without scanning the frame /// again. template @@ -297,8 +429,8 @@ template /// Plan every iteration of \a iterations over \a frame in slices of /// \a sliceWidthBlocks grid blocks (`GridGeometry::blocksPerSlice` of the -/// configured width) with the halo the frame's reach needs -/// (`SliceReach::haloPS`) -- the vertexing pass too, each +/// configured width) with the halo the iterations' chains need +/// (`seedingReach`). The vertexing pass uses the same planner, each /// slice finding its core's frames' vertices (`OwnedFrames`). \a bounds are /// the frame's (`frameBounds`, as the measurement producer ships them); \a /// windowSettings are the settings each iteration's parameters were derived @@ -320,12 +452,12 @@ template plan.layerMaxWidthPS = bounds.widthPS; plan.layerTargetBounds = bounds.target; plan.layerMaxLocVariance = bounds.varLoc; - const auto reach = sliceReach(bounds, frame.grid().geometry()); - plan.haloPS = reach.haloPS(); + const auto reach = seedingReach(bounds, frame.grid().geometry(), iterations); + plan.haloPS = reach.haloPS; const auto width = std::max(1, sliceWidthBlocks); for (std::int32_t begin = 0; begin < plan.blockCount; begin += width) { const typename TimeFrame::TimeSlice slice{frame, {.begin = begin, .end = std::min(plan.blockCount, begin + width)}, plan.haloPS}; - plan.slices.push_back(planSlice(frame, slice, reach.gatePS())); + plan.slices.push_back(planSlice(frame, slice, reach.gatePS)); } return planWithVertices(std::move(plan), windowSettings, vertices); } diff --git a/Detectors/GenericTracking/tracking/test/CMakeLists.txt b/Detectors/GenericTracking/tracking/test/CMakeLists.txt index e8466e6947cc8..488027c86cb39 100644 --- a/Detectors/GenericTracking/tracking/test/CMakeLists.txt +++ b/Detectors/GenericTracking/tracking/test/CMakeLists.txt @@ -60,5 +60,6 @@ gtrk_tracking_test(hypothesis-refit testHypothesisRefit.cxx O2::ReconstructionDa gtrk_tracking_test(passive-scattering testPassiveScattering.cxx) gtrk_tracking_test(displaced-pair testDisplacedPair.cxx) gtrk_tracking_test(follow testFollow.cxx) +gtrk_tracking_test(inactive-layers testInactiveLayers.cxx) add_subdirectory(device) diff --git a/Detectors/GenericTracking/tracking/test/testDeviceArena.cxx b/Detectors/GenericTracking/tracking/test/testDeviceArena.cxx index e1be97a32bfe1..340ea676ad744 100644 --- a/Detectors/GenericTracking/tracking/test/testDeviceArena.cxx +++ b/Detectors/GenericTracking/tracking/test/testDeviceArena.cxx @@ -58,6 +58,7 @@ class NoRuntime final : public DeviceRuntime [[nodiscard]] std::unique_ptr> makeITSTracker(DeviceBlock /*block*/) final { fail(); } [[nodiscard]] std::unique_ptr> makeMFTTracker(DeviceBlock /*block*/) final { fail(); } [[nodiscard]] std::unique_ptr> makeTRKFT3Tracker(DeviceBlock /*block*/) final { fail(); } + [[nodiscard]] std::unique_ptr> makeTRKFT3TOFTracker(DeviceBlock /*block*/) final { fail(); } [[nodiscard]] std::unique_ptr> makeTRKFT3DecayFitter(DeviceBlock /*block*/) final { fail(); } DeviceProperties mProperties; diff --git a/Detectors/GenericTracking/tracking/test/testInactiveLayers.cxx b/Detectors/GenericTracking/tracking/test/testInactiveLayers.cxx new file mode 100644 index 0000000000000..a0ec92e28108a --- /dev/null +++ b/Detectors/GenericTracking/tracking/test/testInactiveLayers.cxx @@ -0,0 +1,452 @@ +// Copyright 2019-2020 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 testInactiveLayers.cxx +/// \brief Inactive layers (LayerSpec.h), as ALICE 3's TOF in TRKFT3TOF: never +/// a hole, outside the other layers' material slabs, found by the +/// follow between two rows of a road that straddles one (the interior +/// row) and after the outward walk (the tail). +/// +/// ToyInactive8 is ToyBarrel8's eight layers with layers 3 and 7 inactive: +/// layer 3 sits between 2 and 4, which also link directly (2 -> 4); layer 7 +/// is the last, as ALICE 3's oTOF. + +#define BOOST_TEST_DYN_LINK +#define BOOST_TEST_MODULE Test GTRK inactive layers +#include "GenericTracking/Base/ElementaryMath.h" +#include "GenericTracking/Base/Geometry.h" +#include "GenericTracking/Tracking/CpuBackend.h" +#include "GenericTracking/Tracking/Follow.h" +#include "GenericTracking/Tracking/Iteration.h" +#include "GenericTracking/Tracking/KFTrackFitter.h" +#include "GenericTracking/Tracking/LayerMaterial.h" +#include "GenericTracking/Tracking/LinkHoles.h" +#include "GenericTracking/Tracking/MeasurementGridBuilder.h" +#include "GenericTracking/Tracking/SensorCells.h" +#include "GenericTracking/Tracking/SlicePlan.h" +#include "GenericTracking/Tracking/TrackingSurface.h" + +#include "AnalyticLayout.h" +#include "GridTestSupport.h" +#include "SerialReferences.h" +#include "ToyBarrel8.h" +#include "UniformMaterial.h" + +#include "CommonConstants/PhysicsConstants.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace o2::gtrk +{ + +namespace detectors +{ + +/// ToyBarrel8 with layers 3 and 7 inactive (see above). +struct ToyInactive8 { + static constexpr const char* name = "ToyInactive8"; + static constexpr auto barrelSpecs = ToyBarrel8::barrelSpecs; + static constexpr std::array discSpecs{}; + static constexpr std::uint64_t inactiveLayers = (std::uint64_t{1} << 3U) | (std::uint64_t{1} << 7U); + static constexpr std::array layerLinks{{ + {.from = 0, .to = 1, .sourceMin = -1.50, .sourceMax = 1.50, .skipsLayer = false}, + {.from = 1, .to = 2, .sourceMin = -1.50, .sourceMax = 1.50, .skipsLayer = false}, + {.from = 2, .to = 3, .sourceMin = -1.50, .sourceMax = 1.50, .skipsLayer = false}, + {.from = 2, .to = 4, .sourceMin = -1.50, .sourceMax = 1.50, .skipsLayer = true}, + {.from = 3, .to = 4, .sourceMin = -1.50, .sourceMax = 1.50, .skipsLayer = false}, + {.from = 4, .to = 5, .sourceMin = -1.50, .sourceMax = 1.50, .skipsLayer = false}, + {.from = 5, .to = 6, .sourceMin = -1.50, .sourceMax = 1.50, .skipsLayer = false}, + {.from = 6, .to = 7, .sourceMin = -1.50, .sourceMax = 1.50, .skipsLayer = false}, + }}; + static constexpr auto barrelLayers = placedLayers(barrelSpecs); + static constexpr auto discLayers = placedLayers(discSpecs); + static constexpr int nSensors = countSensors(barrelLayers, discLayers); +}; + +inline const bool kToyInactive8Published = publishToy(); + +} // namespace detectors + +namespace +{ + +using Det = detectors::ToyInactive8; +using Frame = TimeFrame; +constexpr std::size_t kLayers = 8U; +constexpr std::size_t kMaxClusters = maxChainLayers; +using Tracks = BoundedColumns::template RecordT>; +using Proposal = FollowProposal; + +const TrackingGeometry& trackingGeometry() +{ + static const auto detector = toyGeometry(); + static const TrackingGeometry tracking{detector}; + return tracking; +} + +const SensorCells& cells() +{ + static const SensorCells sensorCells(trackingGeometry()); + return sensorCells; +} + +struct Hit { + LayerID layer = kInvalidLayerID; + SensorID surface = kInvalidSensorID; + Scalar x = 0.F; + Scalar y = 0.F; + Scalar z = 0.F; + Scalar loc0 = 0.F; + Scalar loc1 = 0.F; + TimeEstPS time = test::toyTimeBox(test::kToyTrackTimeNS); +}; + +/// A helix from the origin at 2 T on every layer: the first sensor whose +/// plane it meets inside its bounds (as ToyBarrel8Fixture.h's `sensorHelixHits`). +std::vector helixHits(double phi0, double slope, double ptGeV) +{ + const auto& tracking = trackingGeometry(); + const double curvature = 1. / curvatureRadius(ptGeV, 20.); + const auto at = [&](double arc, double position[3]) { + const double direction = phi0 + (curvature * arc); + position[0] = (std::sin(direction) - std::sin(phi0)) / curvature; + position[1] = (std::cos(phi0) - std::cos(direction)) / curvature; + position[2] = slope * arc; + }; + std::vector hits; + for (std::size_t layer = 0; layer < kLayers; ++layer) { + const auto id = static_cast(layer); + const double crossing = 2. * std::asin(0.5 * curvature * layerDistance(id)) / curvature; + for (SensorID sensor = firstSensorOfLayer(id); sensor < firstSensorOfLayer(static_cast(layer + 1)); ++sensor) { + const auto& surface = tracking.surface(sensor); + const auto height = [&](double arc) { + double position[3]{}; + at(arc, position); + double result = 0.; + for (int i = 0; i < 3; ++i) { + result += (position[i] - static_cast(surface.origin[i])) * static_cast(surface.normal[i]); + } + return result; + }; + double low = 0.8 * crossing; + double high = 1.3 * crossing; + if ((height(low) < 0.) == (height(high) < 0.)) { + continue; + } + for (int i = 0; i < 100; ++i) { + const double middle = 0.5 * (low + high); + ((height(middle) < 0.) == (height(low) < 0.) ? low : high) = middle; + } + double position[3]{}; + at(0.5 * (low + high), position); + const Scalar global[3]{static_cast(position[0]), static_cast(position[1]), static_cast(position[2])}; + Scalar local[3]{}; + surfaceToLocal(surface, global, local); + if (!surface.bounds.isInside(local[0], local[1])) { + continue; + } + hits.push_back({.layer = id, .surface = sensor, .x = global[0], .y = global[1], .z = global[2], .loc0 = local[0], .loc1 = local[1]}); + break; + } + } + return hits; +} + +SearchWindowParams windowParameters() +{ + SearchWindowParams result; + result.minPtGeV = 1.; + result.bzKiloGauss = 20.; + result.materialX2X0 = 0.; + result.positionSigma = 0.003; + result.nSigma = 3.; + return result; +} + +/// One timeframe of \a hits, a measurement each: its cluster index its hit's. +struct Fixture { + explicit Fixture(const std::vector& hits) + : geometry(test::cappedGrid(20., test::withToyFrames(GridParams{.blockWidth = 20'000}), windowParameters(), VertexConstraint{.z = 0., .sigmaZ = 0.02, .sigmaTransverse = 0.001}, 16, 8)), + offsets(static_cast(geometry.bucketCount()) + 1U), + frame(test::frameOf( + geometry, hits.size(), + [&](std::size_t i) { + const auto& hit = hits[i]; + double phi = std::atan2(hit.y, hit.x); + if (phi < 0.) { + phi += kTwoPi; + } + return toybarrel8InputPoint(hit, static_cast(phi)); + }, + [&](std::size_t i) { return hits[i].time; }, + [](std::size_t /*i*/) { return test::PointVariances{.z = 1.e-6F, .r = 2.e-6F, .rPhi = 1.e-6F}; }, + columns, offsets, + [&](std::size_t i, std::uint32_t row) { + columns.surface[row] = hits[i].surface; + columns.loc0[row] = hits[i].loc0; + columns.loc1[row] = hits[i].loc1; + columns.varLoc0[row] = 1.e-6F; + columns.varLoc1[row] = 1.e-6F; + })) + { + } + + struct InputPoint { + LayerID layer = kInvalidLayerID; + Scalar x = 0.F; + Scalar y = 0.F; + Scalar z = 0.F; + Scalar r = 0.F; + Scalar phi = 0.F; + }; + static InputPoint toybarrel8InputPoint(const Hit& hit, Scalar phi) { return {.layer = hit.layer, .x = hit.x, .y = hit.y, .z = hit.z, .r = std::hypot(hit.x, hit.y), .phi = phi}; } + + [[nodiscard]] std::uint32_t row(std::size_t layer) const { return static_cast(std::ranges::find(columns.clusterIndex, static_cast(layer)) - columns.clusterIndex.begin()); } + + GridGeometry geometry; + std::vector offsets; + MeasurementStore columns; + std::unique_ptr frame; +}; + +/// The track of \a fixture's rows on \a layers, innermost first, fitted. +Tracks fittedTrack(const Fixture& fixture, std::initializer_list layers, const std::shared_ptr& pool) +{ + ClusterList rows; + std::ranges::fill(rows.index, ClusterList::kNoCluster); + std::uint8_t count = 0; + for (const auto layer : layers) { + rows.index[count++] = fixture.row(layer); + } + const auto fit = fitMeasurements(Propagator{}, trackingGeometry(), UniformMaterial{}, RowChain{.frame = fixture.frame.get(), .rows = rows.index}, count); + BOOST_REQUIRE(fit.status == PropagationStatus::kOk); + Tracks tracks; + tracks.setMemoryResource(pool.get()); + tracks.resize(1U); + auto view = tracks.view(); + view.state[0] = fit.state; + view.outwardState[0] = fit.outwardState; + view.chi2[0] = fit.chi2; + view.ndf[0] = fit.ndf; + view.status[0] = fit.status; + view.clusters[0] = rows; + view.count[0] = count; + view.iteration[0] = 0U; + view.addedOutward[0] = 0U; + view.addedInward[0] = 0U; + return tracks; +} + +IterationParameters followParameters() +{ + IterationSettings settings{.windows = windowParameters(), .vertexSource = VertexSource::kBeamLine}; + settings.follow = true; + return iterationParameters(settings, VertexConstraint{}, scatteringTable(uniformLayerMaterial(0.))); +} + +Proposal followTrack(const Fixture& fixture, const Tracks& tracks, const std::vector& used, const IterationParameters& parameters) +{ + const auto widths = frameBounds(*fixture.frame).widthPS; + std::vector proposals(tracks.size()); + const UniformMaterial material; + const FollowStage stage{¶meters, fixture.frame.get(), &trackingGeometry(), &material, Propagator{}, tracks.view(), used.data(), widths.data(), cells().view(), proposals.data(), true, 0U, nullptr}; + stage(0U); + return proposals.front(); +} + +} // namespace + +/// Both the interior row and the tail use the iteration's cluster gate. +BOOST_AUTO_TEST_CASE(InactiveLayersUseTheIterationsClusterGate) +{ + static_assert(Detector::isInactiveLayer(3) && Detector::isInactiveLayer(7) && !Detector::isInactiveLayer(2)); + static_assert(Detector::inactiveLayers == 0U); + auto hits = helixHits(0.42, 0.025, 1.8); + BOOST_REQUIRE(hits.size() == kLayers); + for (const std::size_t layer : {3U, 7U}) { + hits[layer].z += 0.002F; + hits[layer].loc1 += 0.002F; + } + const Fixture fixture{hits}; + const auto pool = std::make_shared(); + const auto tracks = fittedTrack(fixture, {0, 1, 2, 4, 5}, pool); + const std::vector used(fixture.frame->size(), kFree); + auto parameters = followParameters(); + + const auto accepted = followTrack(fixture, tracks, used, parameters); + BOOST_TEST(accepted.interior == fixture.row(3)); + BOOST_REQUIRE_EQUAL(static_cast(accepted.outwardCount), 2); + BOOST_TEST(accepted.outward[1] == fixture.row(7)); + + parameters.clusterChi2Max = 0.1F; + const auto rejected = followTrack(fixture, tracks, used, parameters); + BOOST_TEST(rejected.interior == ClusterList::kNoCluster); + BOOST_REQUIRE_EQUAL(static_cast(rejected.outwardCount), 1); + BOOST_TEST(rejected.outward[0] == fixture.row(6)); +} + +/// A pair crossing an inactive layer has no hole there: 2 -> 4 skips +/// layer 3 and crosses nothing; in ToyBarrel8's numbering a 2 -> 4 pair +/// would cross layer 3. +BOOST_AUTO_TEST_CASE(AnInactiveLayerIsNeverAHole) +{ + BOOST_TEST(linkHoleLayers(2, 4) == 0U); + BOOST_TEST(linkHoleLayers(2, 4) == (std::uint64_t{1} << 3U)); + BOOST_TEST(linkHoleLayers(1, 4) == (std::uint64_t{1} << 2U)); +} + +/// A layer's material slab reaches past an inactive neighbour, as in the +/// layout without it: layer 2 (6 cm) to halfway to layer 4 (10 cm), layer 4 +/// from there; layer 6 mirrors its inner half-gap past the inactive layer 7. +BOOST_AUTO_TEST_CASE(AnInactiveLayerIsOutsideTheOtherLayersSlabs) +{ + const auto two = layerSlab(2); + const auto four = layerSlab(4); + const auto six = layerSlab(6); + BOOST_TEST(two.low == 5., boost::test_tools::tolerance(1.e-9)); + BOOST_TEST(two.high == 8., boost::test_tools::tolerance(1.e-9)); + BOOST_TEST(four.low == 8., boost::test_tools::tolerance(1.e-9)); + BOOST_TEST(four.high == 11., boost::test_tools::tolerance(1.e-9)); + BOOST_TEST(six.low == 13., boost::test_tools::tolerance(1.e-9)); + BOOST_TEST(six.high == 15., boost::test_tools::tolerance(1.e-9)); + // ToyBarrel8's layer 2 stops halfway to its layer 3. + BOOST_TEST(layerSlab(2).high == 7., boost::test_tools::tolerance(1.e-9)); +} + +/// A road on 0, 1, 2, 4, 5 straddles the inactive layer 3 through the direct +/// 2 -> 4 link: the follow proposes its row there, before row 4, and the +/// rows beyond the road outward, 6 and 7. +BOOST_AUTO_TEST_CASE(TheFollowTakesTheInteriorRowAndTheTail) +{ + const auto hits = helixHits(0.42, 0.025, 1.8); + BOOST_REQUIRE(hits.size() == kLayers); + const Fixture fixture{hits}; + const auto pool = std::make_shared(); + const auto tracks = fittedTrack(fixture, {0, 1, 2, 4, 5}, pool); + const std::vector used(fixture.frame->size(), kFree); + const auto proposal = followTrack(fixture, tracks, used, followParameters()); + BOOST_TEST(proposal.interior == fixture.row(3)); + BOOST_TEST(proposal.interiorAt == 3U); + BOOST_REQUIRE_EQUAL(static_cast(proposal.outwardCount), 2); + BOOST_TEST(proposal.outward[0] == fixture.row(6)); + BOOST_TEST(proposal.outward[1] == fixture.row(7)); + BOOST_TEST(proposal.inwardCount == 0U); +} + +/// Without their rows the inactive layers cost nothing: no interior row, no +/// hole on layer 7 with none allowed, and the track keeps layer 6's row. +BOOST_AUTO_TEST_CASE(WithoutTheirRowsTheInactiveLayersCostNothing) +{ + const auto hits = helixHits(0.42, 0.025, 1.8); + BOOST_REQUIRE(hits.size() == kLayers); + const Fixture fixture{hits}; + const auto pool = std::make_shared(); + const auto tracks = fittedTrack(fixture, {0, 1, 2, 4, 5}, pool); + std::vector used(fixture.frame->size(), kFree); + used[fixture.row(3)] = kExclusive; + used[fixture.row(7)] = kExclusive; + const auto proposal = followTrack(fixture, tracks, used, followParameters()); + BOOST_TEST(proposal.interior == ClusterList::kNoCluster); + BOOST_REQUIRE_EQUAL(static_cast(proposal.outwardCount), 1); + BOOST_TEST(proposal.outward[0] == fixture.row(6)); +} + +/// The tail: where the outward walk ends before an inactive layer -- here a +/// hole on layer 6, whose row another track holds, with none allowed -- a +/// step from the walk's last state onto the inactive layers it has no row on +/// takes layer 7's row. +BOOST_AUTO_TEST_CASE(TheTailReachesTheInactiveLayerPastTheWalksEnd) +{ + const auto hits = helixHits(0.42, 0.025, 1.8); + BOOST_REQUIRE(hits.size() == kLayers); + const Fixture fixture{hits}; + const auto pool = std::make_shared(); + const auto tracks = fittedTrack(fixture, {0, 1, 2, 3, 4, 5}, pool); + std::vector used(fixture.frame->size(), kFree); + used[fixture.row(6)] = kExclusive; + const auto proposal = followTrack(fixture, tracks, used, followParameters()); + BOOST_REQUIRE_EQUAL(static_cast(proposal.outwardCount), 1); + BOOST_TEST(proposal.outward[0] == fixture.row(7)); + // Taken too, the tail finds nothing. + used[fixture.row(7)] = kExclusive; + BOOST_TEST(followTrack(fixture, tracks, used, followParameters()).outwardCount == 0U); +} + +/// Layer 6's hole drops the row on layer 5. The tail can take layer 7 +/// whose time overlaps the retained rows but is disjoint from layer 5's. +BOOST_AUTO_TEST_CASE(TheTailUsesTheTimeBoxBeforeTheUnconfirmedRow) +{ + auto hits = helixHits(0.42, 0.025, 1.8); + BOOST_REQUIRE(hits.size() == kLayers); + hits[5].time = {.start = 4'000U, .width = 2'000U}; + hits[7].time = {.start = 10'000U, .width = 2'000U}; + const Fixture fixture{hits}; + const auto pool = std::make_shared(); + const auto tracks = fittedTrack(fixture, {0, 1, 2, 3}, pool); + std::vector used(fixture.frame->size(), kFree); + used[fixture.row(6)] = kExclusive; + const auto proposal = followTrack(fixture, tracks, used, followParameters()); + BOOST_REQUIRE_EQUAL(static_cast(proposal.outwardCount), 2); + BOOST_TEST(proposal.outward[0] == fixture.row(4)); + BOOST_TEST(proposal.outward[1] == fixture.row(7)); +} + +/// A road already on the inactive layer has no interior row to find: the +/// follow adds what lies beyond it, as on any layer. +BOOST_AUTO_TEST_CASE(ARoadOnTheInactiveLayerHasNoInteriorRow) +{ + const auto hits = helixHits(1.1, -0.02, 2.2); + BOOST_REQUIRE(hits.size() == kLayers); + const Fixture fixture{hits}; + const auto pool = std::make_shared(); + const auto tracks = fittedTrack(fixture, {0, 1, 2, 3, 4, 5}, pool); + const std::vector used(fixture.frame->size(), kFree); + const auto proposal = followTrack(fixture, tracks, used, followParameters()); + BOOST_TEST(proposal.interior == ClusterList::kNoCluster); + BOOST_REQUIRE_EQUAL(static_cast(proposal.outwardCount), 2); + BOOST_TEST(proposal.outward[1] == fixture.row(7)); +} + +/// The follow's passes (`Follow::run`): the track takes its interior row in +/// path order, between rows 2 and 4, and the outward rows, and owns them. +BOOST_AUTO_TEST_CASE(TheTrackHoldsItsInteriorRowInPathOrderAndOwnsIt) +{ + const auto hits = helixHits(0.42, 0.025, 1.8); + BOOST_REQUIRE(hits.size() == kLayers); + const Fixture fixture{hits}; + const auto pool = std::make_shared(); + auto tracks = fittedTrack(fixture, {0, 1, 2, 4, 5}, pool); + std::vector used(fixture.frame->size(), kFree); + const auto parameters = followParameters(); + Follow follow; + follow.setMemoryPool(pool); + const auto status = follow.run(SerialForEach{}, parameters, *fixture.frame, trackingGeometry(), UniformMaterial{}, Propagator{}, tracks, 0U, true, false, used, frameBounds(*fixture.frame).widthPS, cells().view()); + BOOST_REQUIRE(status == StageStatus::kComplete); + const auto view = tracks.view(); + BOOST_REQUIRE_EQUAL(static_cast(view.count[0]), kLayers); + for (std::size_t layer = 0; layer < kLayers; ++layer) { + BOOST_TEST(view.clusters[0].index[layer] == fixture.row(layer)); + // The follow owns the rows it adds; the road's are the selection's. + const bool added = layer == 3U || layer == 6U || layer == 7U; + BOOST_TEST(used[fixture.row(layer)] == (added ? kExclusive : kFree)); + } +} + +} // namespace o2::gtrk diff --git a/Detectors/GenericTracking/tracking/test/testIteration.cxx b/Detectors/GenericTracking/tracking/test/testIteration.cxx index c0e6d959820b5..81d7b89e76594 100644 --- a/Detectors/GenericTracking/tracking/test/testIteration.cxx +++ b/Detectors/GenericTracking/tracking/test/testIteration.cxx @@ -300,6 +300,108 @@ BOOST_AUTO_TEST_CASE(LayersSharingFramesDoNotReach) BOOST_TEST(shiftedReach.backwardPS == 3 * std::int64_t{longPS}); } +/// The reach of iterations is each one's along the links it takes: on the +/// layers of LayersSharingFramesDoNotReach, iterations on the 22-BC layers +/// alone or on the 81-BC layers alone take no reaching link (gate 0), however +/// the layout links the two groups; one across them reaches as every link +/// does; and of several, the largest. +BOOST_AUTO_TEST_CASE(AnIterationReachesAlongTheLinksItTakes) +{ + using Det = detectors::ToyBarrel8; + constexpr FrameTiming kShort{.lengthBC = 22, .firstStartBC = 0}; + constexpr FrameTiming kLong{.lengthBC = 81, .firstStartBC = 0}; + const auto shortPS = static_cast(psOfBC(22)); + const auto longPS = static_cast(psOfBC(81)); + const auto grid = chainGrid({kShort, kShort, kShort, kLong, kLong, kLong, kLong, kLong}); + const auto bounds = framedBounds({shortPS, shortPS, shortPS, longPS, longPS, longPS, longPS, longPS}); + const auto taking = [](std::uint64_t mask) { + IterationSettings settings; + settings.layerMask = mask; + settings.minClusters = 3; + const auto taken = takenLinks(settings); + IterationParameters parameters; + std::uint32_t kept = 0U; + for (std::size_t layer = 0; layer < IterationParameters::kLayerCount; ++layer) { + parameters.outLinkOffsets[layer] = kept; + for (auto i = outLinks.begin(static_cast(layer)); i < outLinks.end(static_cast(layer)); ++i) { + if (taken[outLinks.links[i]]) { + parameters.outLinkIndices[kept++] = static_cast(outLinks.links[i]); + } + } + } + parameters.outLinkOffsets[IterationParameters::kLayerCount] = kept; + return parameters; + }; + const std::vector> inner{taking(0x07U)}; + const std::vector> outer{taking(0xF8U)}; + const std::vector> across{taking(0xFFU)}; + const std::vector> both{taking(0x07U), taking(0xF8U)}; + const auto seeding = [&](const std::vector>& iterations) { return seedingReach(bounds, grid, std::span>{iterations}); }; + BOOST_TEST(seeding(inner).gatePS == 0); + BOOST_TEST(seeding(outer).gatePS == 0); + BOOST_TEST(seeding(both).gatePS == 0); + BOOST_TEST(sliceReach(bounds, grid).gatePS() == std::int64_t{shortPS} + longPS); + // Across: 2 -> 3 the short frame forward and the long one backward. + BOOST_TEST(seeding(across).gatePS == std::int64_t{shortPS} + longPS); + BOOST_TEST(seeding(across).haloPS == std::int64_t{shortPS} + (2 * std::int64_t{longPS})); + BOOST_TEST(seeding({}).gatePS == sliceReach(bounds, grid).gatePS()); + BOOST_TEST(seeding({}).haloPS == sliceReach(bounds, grid).haloPS()); +} + +/// Of several iterations the gate is the largest of their gates, each its own +/// `R+ + R-` -- not the largest `R+` plus the largest `R-`: one iteration on +/// layers 3-6 across a narrow-box layer 5 of 1 BC frames (`R+` the long frame, +/// `R-` the narrow box: its link out goes nowhere on in the iteration), one +/// on layers 0-3 across the short-long frame edge (`R+` the short frame, `R-` +/// the long one). +BOOST_AUTO_TEST_CASE(TheGateIsTheLargestIterationsNotItsLargestParts) +{ + using Det = detectors::ToyBarrel8; + constexpr FrameTiming kShort{.lengthBC = 22, .firstStartBC = 0}; + constexpr FrameTiming kLong{.lengthBC = 81, .firstStartBC = 0}; + constexpr FrameTiming kNarrow{.lengthBC = 1, .firstStartBC = 0}; + const std::int64_t shortPS = psOfBC(22); + const std::int64_t longPS = psOfBC(81); + const std::int64_t narrowPS = psOfBC(1); + const auto grid = chainGrid({kShort, kShort, kShort, kLong, kLong, kNarrow, kLong, kLong}); + auto bounds = framedBounds({static_cast(shortPS), static_cast(shortPS), static_cast(shortPS), static_cast(longPS), static_cast(longPS), + static_cast(narrowPS), static_cast(longPS), static_cast(longPS)}); + bounds.rowsAreFrames[5] = false; + const auto taken = [](std::uint64_t mask) { + IterationSettings settings; + settings.layerMask = mask; + settings.minClusters = 3; + return takenLinks(settings); + }; + const auto narrow = chainReach(bounds, grid, taken(0x78U)); + BOOST_TEST(narrow.forwardPS == longPS); + BOOST_TEST(narrow.backwardPS == narrowPS); + // Pairwise the link out of the narrow layer reaches the long frame back. + const auto narrowLinks = taken(0x78U); + BOOST_TEST(sliceReach(bounds, grid, &narrowLinks).backwardPS == narrowPS + longPS); + const auto edge = chainReach(bounds, grid, taken(0x0FU)); + BOOST_TEST(edge.forwardPS == shortPS); + BOOST_TEST(edge.backwardPS == longPS); + std::vector> iterations(2); + for (std::size_t i = 0; i < 2; ++i) { + const auto links = taken(i == 0 ? 0x78U : 0x0FU); + std::uint32_t kept = 0U; + for (std::size_t layer = 0; layer < IterationParameters::kLayerCount; ++layer) { + iterations[i].outLinkOffsets[layer] = kept; + for (auto o = outLinks.begin(static_cast(layer)); o < outLinks.end(static_cast(layer)); ++o) { + if (links[outLinks.links[o]]) { + iterations[i].outLinkIndices[kept++] = static_cast(outLinks.links[o]); + } + } + } + iterations[i].outLinkOffsets[IterationParameters::kLayerCount] = kept; + } + const auto seeding = seedingReach(bounds, grid, std::span>{iterations}); + BOOST_TEST(seeding.gatePS == std::max(longPS + narrowPS, shortPS + longPS)); + BOOST_TEST(seeding.gatePS < 2 * longPS); + BOOST_TEST(seeding.haloPS == std::max(narrow.haloPS(), edge.haloPS())); +} + /// A layer whose rows are not exactly its frames -- widened by a margin the /// producer applied, whatever the configuration says now -- reaches on both /// of its links. diff --git a/Detectors/GenericTracking/tracking/test/testIterations.cxx b/Detectors/GenericTracking/tracking/test/testIterations.cxx index 7e3d39e336b86..fe5ad9c704cef 100644 --- a/Detectors/GenericTracking/tracking/test/testIterations.cxx +++ b/Detectors/GenericTracking/tracking/test/testIterations.cxx @@ -427,8 +427,18 @@ BOOST_AUTO_TEST_CASE(ASlicePlanHoldsTheSlicesBoundsAndGate) const auto plan = tracker->planTimeframe(*fixture.frame, frameBounds(*fixture.frame), {}, 3); const auto& frame = *fixture.frame; BOOST_TEST(plan.slices.size() == static_cast((fixture.geometry.blockCount() + 2) / 3)); - // The toys' blocks start at 0 and are whole picoseconds. - const auto reach = sliceReach(frameBounds(frame), fixture.geometry).gatePS(); + // The toys' blocks start at 0 and are whole picoseconds. The gate is the + // iterations' chains' (`chainReach`): the toy's rows are boxes of one width, + // not frames, so a link reaches that width and so does a triplet's two, and + // along the eight layers a chain drifts 4 widths each way -- 7 pairwise. + const std::vector> parameters{tracker->iteration(0U), tracker->iteration(1U)}; + const auto chains = chainReach(frameBounds(frame), fixture.geometry, takenLinks(iterations().front())); + BOOST_TEST(seedingReach(frameBounds(frame), fixture.geometry, std::span>{parameters}).gatePS == chains.gatePS()); + const std::int64_t boxPS = test::kToyBoxWidthPS; + BOOST_TEST(chains.forwardPS == 4 * boxPS); + BOOST_TEST(chains.backwardPS == 4 * boxPS); + BOOST_TEST(sliceReach(frameBounds(frame), fixture.geometry).forwardPS == 7 * boxPS); + const auto reach = chains.gatePS(); const auto width = fixture.geometry.blockWidth(); BOOST_REQUIRE(fixture.geometry.partsPerPS() == 1); for (const auto& slicePlan : plan.slices) { @@ -736,9 +746,9 @@ struct FramedRun { std::int64_t haloPS = 0; }; -FramedRun trackFramed(const Fixture& fixture, std::int32_t widthBlocks) +FramedRun trackFramed(const Fixture& fixture, std::int32_t widthBlocks, const std::vector& settings = iterations()) { - auto tracker = makeTracker(iterations(), false); + auto tracker = makeTracker(settings, false); const auto result = tracker->run(*fixture.frame, tracker->planTimeframe(*fixture.frame, frameBounds(*fixture.frame), {}, widthBlocks)); BOOST_REQUIRE(result.status == StageStatus::kComplete); FramedRun run{.tracks = found(result), .times = std::vector(kCrossingBC.size()), .haloPS = result.iterations.front().haloPS}; @@ -798,6 +808,103 @@ BOOST_AUTO_TEST_CASE(TwoFrameLengthsSliceWithOneOuterFrameOfHalo) } } +/// The two-length toy with one outer layer of narrow boxes, as a TOF layer +/// between two of the same frames: its grid frames 1 BC, each hit's box the +/// BC before its time, [t - 1 BC, t], at the hit's picosecond, not a frame. +/// The crossings at 81, 162, 243, 324 and 648 BC -- outer frames' starts, +/// blocks' at 162, 324, 648 -- give narrow boxes straddling an outer frame's +/// edge, and a block's. A triplet's third box overlaps its first, so through +/// the narrow layer the two outer layers beside it stay in one frame. +/// +/// On the outer layers alone (3-7, every frame 81 BC, as ALICE 3's ML 3-7 +/// pass with the iTOF): pairwise every link into the narrow layer reaches the +/// long frame forward and the narrow box backward, every link out of it the +/// reverse, `R+ = R- = long + narrow`. The chains: into the narrow layer the +/// long frame forward and its box backward; after it, the next layer back in +/// the frame before it, 0. Out of the narrow layer a chain starting on it +/// reaches the long frame backward -- if a link goes on from its target +/// (narrow layer 5: 5 -> 6 -> 7), not for the last link alone (6 -> 7, +/// a tracklet no triplet takes). And on every layer, both iterations: less +/// than pairwise. Each way the slices give the one-slice tracks. +BOOST_AUTO_TEST_CASE(ANarrowBoxLayerBetweenLayersOfTheSameFrames) +{ + constexpr std::array kCrossings{5, 81, 100, 162, 170, 243, 324, 400, 480, 520, 648, 700}; + const auto longPS = psOfBC(kOuterFrameBC); + const auto narrowPS = psOfBC(1); + auto outer = iterations(); + for (auto& iteration : outer) { + iteration.layerMask = 0xF8U; + } + for (const LayerID narrow : {LayerID{6}, LayerID{5}}) { + BOOST_TEST_CONTEXT("narrow layer " << int{narrow}) + { + auto params = twoLengthGrid(); + params.frames[narrow] = {.lengthBC = 1, .firstStartBC = 0}; + const auto boxOf = [&](const Hit& hit) { + if (hit.point.layer != narrow) { + return frameOf(hit, 0); + } + const auto t = std::llround(hit.timeNS * 1000.); + return TimeEstPS{.start = static_cast(t - narrowPS), .width = static_cast(narrowPS)}; + }; + std::vector hits; + for (std::size_t track = 0; track < kCrossings.size(); ++track) { + const auto k = static_cast(track); + const double pt = stiff(track) ? 2. + (0.2 * static_cast(track % 5U)) : 0.4 + (0.06 * static_cast(track % 5U)); + const auto one = sensorHelixHits(std::fmod(0.3 + (0.9 * k), 2 * std::numbers::pi_v), 0.03 * std::cos(1.3 * k), pt, (static_cast(kCrossings[track]) * kBunchNS) + 5.); + BOOST_REQUIRE(one.size() == kLayers); + hits.insert(hits.end(), one.begin(), one.end()); + } + const Fixture fixture{hits, kFramedDurationNS, params, boxOf}; + const auto bounds = frameBounds(*fixture.frame); + BOOST_TEST(!bounds.rowsAreFrames[narrow]); + BOOST_TEST(bounds.widthPS[narrow] == narrowPS); + const auto& geometry = fixture.geometry; + std::size_t acrossFrame = 0, acrossBlock = 0; + for (const auto& hit : hits) { + if (hit.point.layer == narrow) { + const auto box = boxOf(hit); + // The BC a picosecond lies in, rounded down (bcOfPS rounds up: it inverts psOfBC). + const auto bcAt = [](std::int64_t ps) { return (ps * kPSPerBCDenominator) / kPSPerBCNumerator; }; + acrossFrame += bcAt(box.start) / kOuterFrameBC != bcAt(box.start + box.width - 1) / kOuterFrameBC; + acrossBlock += geometry.blockOfPS(box.start) != geometry.blockOfPS(box.start + box.width - 1); + } + } + BOOST_TEST(acrossFrame >= 4U); + BOOST_TEST(acrossBlock >= 2U); + + const auto outerTracker = makeTracker(outer, false); + const auto taken = takenLinks(outer.front()); + for (std::size_t link = 0; link < nLinks; ++link) { + BOOST_TEST(taken[link] == (Det::layerLinks[link].from >= 3)); + } + const auto pairwise = sliceReach(bounds, geometry, &taken); + BOOST_TEST(pairwise.forwardPS == longPS + narrowPS); + BOOST_TEST(pairwise.backwardPS == longPS + narrowPS); + const auto chains = chainReach(bounds, geometry, taken); + BOOST_TEST(chains.forwardPS == longPS); + BOOST_TEST(chains.backwardPS == (narrow == 6 ? narrowPS : longPS)); + BOOST_TEST(outerTracker->planTimeframe(*fixture.frame, bounds, {}, 1).haloPS == chains.haloPS()); + BOOST_TEST(chains.haloPS() < pairwise.haloPS()); + const auto every = makeTracker(iterations(), false)->planTimeframe(*fixture.frame, bounds, {}, 1).haloPS; + BOOST_TEST(every < sliceReach(bounds, geometry).haloPS()); + + const auto everyLayer = iterations(); + for (const auto* settings : std::array*, 2>{&outer, &everyLayer}) { + const auto& chosen = *settings; + BOOST_TEST_CONTEXT((settings == &outer ? "layers 3-7" : "every layer")) + { + const auto whole = trackFramed(fixture, geometry.blockCount(), chosen); + BOOST_TEST(whole.tracks.size() == kCrossings.size()); + for (const std::int32_t width : {1, 2, 3}) { + BOOST_TEST_CONTEXT("slices of " << width << " blocks") { BOOST_TEST((trackFramed(fixture, width, chosen).tracks == whole.tracks)); } + } + } + } + } + } +} + /// The same toy with its boxes widened by a margin while the grid still /// declares the frames -- as a dump keeps the boxes its producer widened, /// whatever margin the tracking is configured with: the rows are not their diff --git a/Detectors/GenericTracking/workflow-trk/CMakeLists.txt b/Detectors/GenericTracking/workflow-trk/CMakeLists.txt index 02eddfe0677ef..344a872efe6e0 100644 --- a/Detectors/GenericTracking/workflow-trk/CMakeLists.txt +++ b/Detectors/GenericTracking/workflow-trk/CMakeLists.txt @@ -11,11 +11,11 @@ # ALICE 3's TRK and FT3 workflow: their sensors, clusters and conditions, the # converter, the measurement producer and the tracker (its unit instantiating -# the tracker). -set(trackerUnits src/TrackerTRKFT3.cxx) +# the tracker); TRKFT3 alone and TRKFT3TOF, with the IOTOF's layers. +set(trackerUnits src/TrackerTRKFT3.cxx src/TrackerTRKFT3TOF.cxx) o2_add_library(GTrkWorkflowTRK - SOURCES src/TRK.cxx ${trackerUnits} - PUBLIC_LINK_LIBRARIES O2::GTrkWorkflow O2::DataFormatsTRKFT3 O2::TRKReconstruction O2::TRKBase + SOURCES src/TRK.cxx src/TRKTOF.cxx ${trackerUnits} + PUBLIC_LINK_LIBRARIES O2::GTrkWorkflow O2::DataFormatsTRKFT3 O2::TRKReconstruction O2::TRKBase O2::DataFormatsIOTOF O2::IOTOFBase PRIVATE_LINK_LIBRARIES O2::FT3Base O2::Field O2::SimulationDataFormat O2::CommonConstants ROOT::Geom TARGETVARNAME targetName) @@ -29,6 +29,6 @@ install(DIRECTORY include/GenericTracking DESTINATION ${CMAKE_INSTALL_INCLUDEDIR o2_add_executable(trk-reco-workflow SOURCES src/gtrk-trk-reco-workflow.cxx COMPONENT_NAME gtrk - PUBLIC_LINK_LIBRARIES O2::GTrkWorkflowTRK O2::DetectorsRaw O2::TRKWorkflow) + PUBLIC_LINK_LIBRARIES O2::GTrkWorkflowTRK O2::DetectorsRaw O2::TRKWorkflow O2::IOTOFWorkflow) add_subdirectory(test) diff --git a/Detectors/GenericTracking/workflow-trk/include/GenericTracking/WorkflowTRK/ConditionsTRK.h b/Detectors/GenericTracking/workflow-trk/include/GenericTracking/WorkflowTRK/ConditionsTRK.h index 44b38bccf8b84..76087047926c5 100644 --- a/Detectors/GenericTracking/workflow-trk/include/GenericTracking/WorkflowTRK/ConditionsTRK.h +++ b/Detectors/GenericTracking/workflow-trk/include/GenericTracking/WorkflowTRK/ConditionsTRK.h @@ -28,8 +28,10 @@ #include "GenericTracking/Base/LayerSpec.h" #include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" #include "GenericTracking/Workflow/Conditions.h" #include "GenericTracking/WorkflowTRK/TRK.h" +#include "GenericTracking/WorkflowTRK/TRKTOF.h" #include "DetectorsBase/GRPGeomHelper.h" #include "DetectorsBase/Propagator.h" @@ -178,6 +180,57 @@ class Conditions [[no_unique_address]] MaterialConditionOf mMaterial; }; +/// ALICE 3's with its TOF layers (TRKTOF.h): TRKFT3's, its frames and +/// depths on TRKFT3TOF's layers, and its own material LUT +/// (`TRK/Param/MatLUTTOF`, MaterialLUT.h), which reaches the TOF. +template +class Conditions +{ + public: + explicit Conditions(std::vector& inputs) : mTrk(inputs) + { + MaterialConditionOf::declare(inputs); + } + + [[nodiscard]] static int orbitsPerTimeframe() { return Conditions::orbitsPerTimeframe(); } + + static constexpr bool kMeanVertex = false; + + [[nodiscard]] static o2::header::DataOrigin origin() { return detectorOrigin(); } + + void init(o2::framework::InitContext& ic) { mTrk.init(ic); } + + void checkUpdates(o2::framework::ProcessingContext& pc) const + { + mTrk.checkUpdates(pc); + MaterialConditionOf::checkUpdates(pc); + } + + void finaliseCCDB(o2::framework::ConcreteDataMatcher& matcher, void* obj) + { + if (!mMaterial.finaliseCCDB(matcher, obj)) { + mTrk.finaliseCCDB(matcher, obj); + } + } + + /// TRKFT3's on its layers, a bunch crossing on the TOF's (TRKTOF.h). + [[nodiscard]] std::vector frameTiming() const { return alice::trktofFrameTiming(mTrk.frameTiming()); } + + /// TRKFT3's on its layers, 0 on the TOF's (TRKTOF.h). + [[nodiscard]] std::vector measurementDepthsCM() const { return alice::trktofMeasurementDepthsCM(mTrk.measurementDepthsCM()); } + + /// The run's material LUT, the CCDB cache's; null before the first timeframe. + [[nodiscard]] const o2::base::MatLayerCylSet* materialLut() const + requires WithMaterial + { + return mMaterial.lut(); + } + + private: + Conditions mTrk; + [[no_unique_address]] MaterialConditionOf mMaterial; +}; + } // namespace o2::gtrk::workflow #endif // GTRK_WORKFLOWS_CONDITIONSTRK_H_ diff --git a/Detectors/GenericTracking/workflow-trk/include/GenericTracking/WorkflowTRK/TRKTOF.h b/Detectors/GenericTracking/workflow-trk/include/GenericTracking/WorkflowTRK/TRKTOF.h new file mode 100644 index 0000000000000..3205be5bf8a8b --- /dev/null +++ b/Detectors/GenericTracking/workflow-trk/include/GenericTracking/WorkflowTRK/TRKTOF.h @@ -0,0 +1,90 @@ +// Copyright 2019-2020 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 TRKTOF.h +/// \brief ALICE 3's tracker with its TOF layers (Detectors/TRKFT3TOF.h): the +/// IOTOF clusters as ours, the layout's frames and depths. +/// +/// **Clusters.** `o2::iotof::Cluster`, one stream (TF3/CLUSTERS/0), each with +/// its absolute bunch crossing and its time in it (`getBc`, `getTimeWrtBc`): +/// `tofClusters` gives each its pixels' mean centre in its chip's frame -- the +/// active matrix's centre, x across the rows, z along the columns, as +/// `placeChips` places the chip -- pitch^2/12 variances, and the +/// time box of the bunch crossing that ends at its time, [t - 1 BC, t]. +/// +/// **Frames and depths.** TRKFT3's on its layers (TRK.h), one bunch crossing +/// at measurement depth 0 on the TOF's: a TOF row's box is its own, never a +/// readout frame. + +#ifndef GTRK_ALICE_TRKTOF_H_ +#define GTRK_ALICE_TRKTOF_H_ + +#include "GenericTracking/Base/FrameTiming.h" +#include "GenericTracking/Clustering/Cluster.h" + +#include +#include +#include +#include + +namespace o2::iotof +{ +class Cluster; +class GeometryTGeo; +} // namespace o2::iotof + +namespace o2::gtrk::alice +{ + +/// Where an IOTOF chip's pixels lie in its frame (`tofClusters`): every +/// chip's the same, from O2's IOTOF GeometryTGeo and ChipSpecificsParam. +struct TofPixelFrame { + std::vector rowX; ///< a row's pixel centre, along the frame's x [cm] + std::vector columnZ; ///< a column's, along its z [cm] + float sigmaX = 0.F; ///< the row pitch over sqrt(12) [cm] + float sigmaZ = 0.F; ///< the column pitch's + std::size_t chips = 0; ///< the IOTOF chips, iTOF and oTOF + + /// From \a geometry: the frame's origin the active matrix's centre. Throws + /// std::runtime_error if the geometry has no chips or pixels. + [[nodiscard]] static TofPixelFrame build(const o2::iotof::GeometryTGeo& geometry); +}; + +/// The clusters `tofClusters` left out, by why. +struct TofSkipped { + std::size_t chip = 0; ///< on no IOTOF chip + std::size_t time = 0; ///< a time in its bunch crossing outside [0, 1 BC) + std::size_t pattern = 0; ///< no pixel fired, or one outside the chip + std::size_t clamped = 0; ///< kept: its box moved into the timeframe + [[nodiscard]] std::size_t total() const { return chip + time + pattern; } +}; + +/// Every usable cluster of \a clusters as ours, in its box's start order +/// (stable), and its index in \a clusters into \a kept: sensor `TRKFT3TOF::kFirstTOFSensor` plus its +/// chip, its position and errors in \a frame, its time box [t - 1 BC, t] in +/// the timeframe starting at orbit \a tfFirstOrbit of \a orbitsPerTimeframe +/// orbits, moved into the timeframe where it reaches past one of its ends +/// (counted). A cluster on no chip, with a time outside its bunch crossing or +/// without a usable pattern is left out and counted in \a skipped. +[[nodiscard]] std::vector tofClusters(std::span clusters, const TofPixelFrame& frame, std::uint32_t tfFirstOrbit, int orbitsPerTimeframe, std::vector& kept, TofSkipped& skipped); + +/// TRKFT3TOF's readout frames: TRKFT3's (\a trk, `trkFrameTiming`) on its +/// layers, one bunch crossing from BC 0 on the TOF's. +[[nodiscard]] std::vector trktofFrameTiming(std::span trk); + +/// TRKFT3TOF's measurement depths [cm]: TRKFT3's (\a trk, +/// `measurementDepthsCM`) on its layers, 0 on the TOF's, whose clusters lie +/// on the sensor's mid-plane. +[[nodiscard]] std::vector trktofMeasurementDepthsCM(std::span trk); + +} // namespace o2::gtrk::alice + +#endif // GTRK_ALICE_TRKTOF_H_ diff --git a/Detectors/GenericTracking/workflow-trk/src/TRK.cxx b/Detectors/GenericTracking/workflow-trk/src/TRK.cxx index 9c1121a9e3a0e..6964a3ef0e421 100644 --- a/Detectors/GenericTracking/workflow-trk/src/TRK.cxx +++ b/Detectors/GenericTracking/workflow-trk/src/TRK.cxx @@ -12,7 +12,8 @@ /// \file TRK.cxx /// \brief ALICE 3's own, TRK's barrel and FT3's discs: its chips placed, its /// cluster format, its dictionaries' depths, frames and field (TRK.h), -/// its cluster converter and its measurement producer. +/// its cluster converter (TrkClusterConverter.h) and its measurement +/// producer. #include "GenericTracking/WorkflowTRK/TRK.h" @@ -27,6 +28,8 @@ #include "GenericTracking/Workflow/MeasurementProducerSpec.h" #include "GenericTracking/WorkflowTRK/ConditionsTRK.h" +#include "TrkClusterConverter.h" + #include "DataFormatsTRKFT3/Cluster.h" #include "DataFormatsTRKFT3/ROFRecord.h" #include "DetectorsRaw/HBFUtils.h" @@ -234,129 +237,12 @@ double alice3BzKiloGauss() namespace o2::gtrk::workflow { -using namespace o2::framework; - -namespace -{ - -/// ALICE 3's TRK and FT3 clusters, one stream per barrel layer and one per -/// disc as O2's cluster readers publish them (TRK/COMPCLUSTERS/, -/// FT3/COMPCLUSTERS/ and the rest), turned into GTRK/TRKCLUSTERS and -/// GTRK/TRKCLUSMCTR: each layer's -/// stream converted with its own readout frames, each cluster with its -/// position and errors from the topology dictionaries, CCDB conditions, -/// then the layers -/// concatenated in order, barrel first, so a measurement's cluster index is -/// its position in that concatenation and the labels follow it. -class TrkClusterConverterTask : public Task -{ - public: - static constexpr int kLayers = Detector::nLayers; - static constexpr int kBarrelLayers = Detector::nBarrelLayers; - - /// Our layer \a layer's stream: TRK's barrel layer, or FT3's disc after them. - [[nodiscard]] static o2::header::DataOrigin originOf(int layer) { return layer < kBarrelLayers ? o2::header::DataOrigin{"TRK"} : o2::header::DataOrigin{"FT3"}; } - [[nodiscard]] static o2::header::DataHeader::SubSpecificationType subspecOf(int layer) { return static_cast(layer < kBarrelLayers ? layer : layer - kBarrelLayers); } - - TrkClusterConverterTask(bool useMC, TrkDictionaryConditions dictionaries, std::shared_ptr geometryRequest) - : mUseMC(useMC), mDictionaries(dictionaries), mGeometryRequest(std::move(geometryRequest)) {} - - void init(InitContext& /*ic*/) final { o2::base::GRPGeomHelper::instance().setRequest(mGeometryRequest); } - - void finaliseCCDB(ConcreteDataMatcher& matcher, void* obj) final - { - if (!o2::base::GRPGeomHelper::instance().finaliseCCDB(matcher, obj)) { - mDictionaries.finaliseCCDB(matcher, obj); - } - } - - void run(ProcessingContext& pc) final - { - o2::base::GRPGeomHelper::instance().checkUpdates(pc); - // Dictionary coordinates use the VD segmentation's petal count, which - // GeometryTGeo derives from the loaded geometry in this device's process. - o2::trk::GeometryTGeo::Instance(); - TrkDictionaryConditions::checkUpdates(pc); - const auto& timing = pc.services().get(); - std::vector clusters; - o2::dataformats::MCTruthContainer labels; - for (int layer = 0; layer < kLayers; ++layer) { - const auto patterns = pc.inputs().get>(std::format("patterns_{}", layer)); - const auto rofs = pc.inputs().get>(std::format("rofs_{}", layer)); - if (rofs.empty()) { - continue; - } - // The timeframe's first orbit as DPL announces it, held to the one the - // frames imply, as for the ITS. - const auto implied = o2::raw::HBFUtils::Instance().getFirstIRofTF(rofs.front().getBCData()).orbit; - if (implied != timing.firstTForbit) { - LOGP(fatal, "TRKFT3 layer {}: the readout frames belong to the timeframe starting at orbit {}, DPL says {}", layer, implied, timing.firstTForbit); - } - const std::span patternBytes{patterns.data(), patterns.size()}; - const auto local = [&]() { - if (layer < kBarrelLayers) { - const auto compact = pc.inputs().get>(std::format("compclusters_{}", layer)); - return alice::trkLocalClusters(std::span{compact.data(), compact.size()}, patternBytes, *mDictionaries.trk()); - } - const auto compact = pc.inputs().get>(std::format("compclusters_{}", layer)); - return alice::ft3LocalClusters(std::span{compact.data(), compact.size()}, patternBytes, *mDictionaries.ft3()); - }(); - const std::span frames{rofs.data(), rofs.size()}; - const auto converted = alice::toClusters(local, frames, alice::readoutFrames(frames), timing.firstTForbit); - clusters.insert(clusters.end(), converted.begin(), converted.end()); - if (mUseMC) { - const auto layerLabels = pc.inputs().get*>(std::format("labels_{}", layer)); - if (layerLabels->getIndexedSize() != converted.size()) { - LOGP(fatal, "TRKFT3 layer {}: {} labelled clusters for {} clusters", layer, layerLabels->getIndexedSize(), converted.size()); - } - labels.mergeAtBack(*layerLabels); - } - } - LOGP(info, "TRKFT3: {} clusters on {} layers for the timeframe at orbit {}", clusters.size(), kLayers, timing.firstTForbit); - pc.outputs().snapshot(Output{gDataOrigin, description(kClusters), 0}, clusters); - if (mUseMC) { - auto& flat = pc.outputs().make>(Output{gDataOrigin, description(kClustersMCTruth), 0}); - labels.flatten_to(flat); - } - } - - private: - bool mUseMC; - TrkDictionaryConditions mDictionaries; - std::shared_ptr mGeometryRequest; -}; - -} // namespace - template <> -DataProcessorSpec getClusterConverterSpec(const ConfigContext& /*context*/, bool useMC) +o2::framework::DataProcessorSpec getClusterConverterSpec(const o2::framework::ConfigContext& /*context*/, bool useMC) { - std::vector inputs; - std::vector outputs{OutputSpec{gDataOrigin, description(kClusters), 0, Lifetime::Timeframe}}; - for (int layer = 0; layer < TrkClusterConverterTask::kLayers; ++layer) { - const auto origin = TrkClusterConverterTask::originOf(layer); - const auto subspec = TrkClusterConverterTask::subspecOf(layer); - inputs.emplace_back(std::format("compclusters_{}", layer), origin, "COMPCLUSTERS", subspec, Lifetime::Timeframe); - inputs.emplace_back(std::format("patterns_{}", layer), origin, "PATTERNS", subspec, Lifetime::Timeframe); - inputs.emplace_back(std::format("rofs_{}", layer), origin, "CLUSTERSROF", subspec, Lifetime::Timeframe); - if (useMC) { - inputs.emplace_back(std::format("labels_{}", layer), origin, "CLUSTERSMCTR", subspec, Lifetime::Timeframe); - } - } - if (useMC) { - outputs.emplace_back(gDataOrigin, description(kClustersMCTruth), 0, Lifetime::Timeframe); - } - const TrkDictionaryConditions dictionaries(inputs); - auto geometryRequest = std::make_shared(false, false, false, false, false, o2::base::GRPGeomRequest::Aligned, inputs); - return DataProcessorSpec{ - .name = deviceName("cluster-converter"), - .inputs = inputs, - .outputs = outputs, - .algorithm = AlgorithmSpec{adaptFromTask(useMC, dictionaries, geometryRequest)}, - .options = Options{}, - }; + return trkClusterConverterSpec(useMC); } -template DataProcessorSpec getMeasurementProducerSpec(); +template o2::framework::DataProcessorSpec getMeasurementProducerSpec(); } // namespace o2::gtrk::workflow diff --git a/Detectors/GenericTracking/workflow-trk/src/TRKTOF.cxx b/Detectors/GenericTracking/workflow-trk/src/TRKTOF.cxx new file mode 100644 index 0000000000000..c0bc81520600e --- /dev/null +++ b/Detectors/GenericTracking/workflow-trk/src/TRKTOF.cxx @@ -0,0 +1,246 @@ +// Copyright 2019-2020 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 TRKTOF.cxx +/// \brief ALICE 3's tracker with its TOF layers (TRKTOF.h): TRKFT3TOF's chips, +/// the IOTOF clusters as ours, frames and depths, its cluster +/// converter and its measurement producer. + +#include "GenericTracking/WorkflowTRK/TRKTOF.h" + +#include "GenericTracking/Base/TimeEstPS.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" +#include "GenericTracking/Alice/Placement.h" +#include "GenericTracking/Workflow/ClusterConverterSpec.h" +#include "GenericTracking/Workflow/GridConfig.h" +#include "GenericTracking/Workflow/MeasurementProducer.h" +#include "GenericTracking/Workflow/MeasurementProducerSpec.h" +#include "GenericTracking/WorkflowTRK/ConditionsTRK.h" + +#include "TrkClusterConverter.h" + +#include "CommonConstants/LHCConstants.h" +#include "DataFormatsIOTOF/Cluster.h" +#include "IOTOFBase/GeometryTGeo.h" +#include "IOTOFBase/IOTOFBaseParam.h" +#include "MathUtils/Cartesian.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace o2::gtrk::alice +{ + +template <> +std::vector placeChips() +{ + using Layout = detectors::TRKFT3TOF; + auto sensors = placeChips(); + for (auto& sensor : sensors) { + sensor.layer = detectors::trkft3tof::fromTRKFT3(sensor.layer); + } + // The IOTOF chips: the plane of O2's sensor volume through the active + // matrix's centre, loc0 along its x (rows), loc1 along its z (columns), the + // normal x cross z, its -y: `tofClusters`' frame (TofPixelFrame). + auto& tof = *o2::iotof::GeometryTGeo::Instance(); + const auto& specs = o2::iotof::ChipSpecificsParam::Instance(); + const auto first = tof.detectorToLocal(0, 0, 0); + const auto last = tof.detectorToLocal(specs.NRows - 1, specs.NCols - 1, 0); + const double cx = (first.X() + last.X()) / 2.F; + const double cz = (first.Z() + last.Z()) / 2.F; + const int chips = tof.getITOFNumberOfChips() + tof.getOTOFNumberOfChips(); + for (int chip = 0; chip < chips; ++chip) { + const auto* placement = tof.extractMatrixSensor(chip); + if (placement == nullptr) { + throw std::runtime_error("TRKFT3TOF: IOTOF chip " + std::to_string(chip) + " has no sensor matrix"); + } + const o2::math_utils::Transform3D matrix(*placement); + using Point = o2::math_utils::Point3D; + const auto origin = matrix * Point{cx, 0., cz}; + const auto axis0 = matrix * Point{cx + 1., 0., cz}; + const auto axis1 = matrix * Point{cx, 0., cz + 1.}; + const double u[3] = {axis0.X() - origin.X(), axis0.Y() - origin.Y(), axis0.Z() - origin.Z()}; + const double v[3] = {axis1.X() - origin.X(), axis1.Y() - origin.Y(), axis1.Z() - origin.Z()}; + const double n[3] = {(u[1] * v[2]) - (u[2] * v[1]), (u[2] * v[0]) - (u[0] * v[2]), (u[0] * v[1]) - (u[1] * v[0])}; + Sensor sensor{}; + for (int i = 0; i < 3; ++i) { + sensor.rot[(3 * i) + 0] = u[i]; + sensor.rot[(3 * i) + 1] = v[i]; + sensor.rot[(3 * i) + 2] = n[i]; + } + sensor.trans[0] = origin.X(); + sensor.trans[1] = origin.Y(); + sensor.trans[2] = origin.Z(); + sensor.layer = tof.getIOTOFLayer(chip) == 0 ? Layout::kInnerTOFLayer : Layout::kOuterTOFLayer; + sensors.push_back(sensor); + } + return sensors; +} + +TofPixelFrame TofPixelFrame::build(const o2::iotof::GeometryTGeo& geometry) +{ + const auto& specs = o2::iotof::ChipSpecificsParam::Instance(); + TofPixelFrame frame; + while (geometry.isValidIOTOFChipIndex(static_cast(frame.chips))) { + ++frame.chips; + } + if (frame.chips == 0 || specs.NRows <= 0 || specs.NCols <= 0) { + throw std::runtime_error(std::format("IOTOF: {} chips of {} x {} pixels in the geometry", frame.chips, specs.NRows, specs.NCols)); + } + // The pixel centres in the chip frame: x depends on the row alone, z on + // the column alone (GeometryTGeo::detectorToLocal), about the active + // matrix's centre (`placeChips`). + const auto first = geometry.detectorToLocal(0, 0, 0); + const auto last = geometry.detectorToLocal(specs.NRows - 1, specs.NCols - 1, 0); + const double cx = (first.X() + last.X()) / 2.; + const double cz = (first.Z() + last.Z()) / 2.; + frame.rowX.resize(static_cast(specs.NRows)); + frame.columnZ.resize(static_cast(specs.NCols)); + for (int row = 0; row < specs.NRows; ++row) { + frame.rowX[static_cast(row)] = static_cast(geometry.detectorToLocal(row, 0, 0).X() - cx); + } + for (int column = 0; column < specs.NCols; ++column) { + frame.columnZ[static_cast(column)] = static_cast(geometry.detectorToLocal(0, column, 0).Z() - cz); + } + frame.sigmaX = static_cast(specs.PitchRow / std::sqrt(12.)); + frame.sigmaZ = static_cast(specs.PitchCol / std::sqrt(12.)); + return frame; +} + +std::vector tofClusters(std::span clusters, const TofPixelFrame& frame, std::uint32_t tfFirstOrbit, int orbitsPerTimeframe, std::vector& kept, TofSkipped& skipped) +{ + constexpr double kBunchNS = o2::constants::lhc::LHCBunchSpacingNS; + const auto firstBC = static_cast(tfFirstOrbit) * o2::constants::lhc::LHCMaxBunches; + const std::int64_t durationPS = workflow::timeframeDurationPS(orbitsPerTimeframe); + const std::int64_t widthPS = psOfBC(1); + std::vector result; + result.reserve(clusters.size()); + kept.clear(); + kept.reserve(clusters.size()); + for (std::size_t index = 0; index < clusters.size(); ++index) { + const auto& cluster = clusters[index]; + const auto chip = cluster.getChipID(); + if (chip >= frame.chips) { + ++skipped.chip; + continue; + } + const float fineNS = cluster.getTimeWrtBc(); + if (!(fineNS >= 0.F && static_cast(fineNS) < kBunchNS)) { + ++skipped.time; + continue; + } + // The fired pixels' mean centre: the pattern is the cluster's + // rows x columns, row-major, from its first row and column. + const unsigned rows = cluster.getRowSpan(); + const unsigned columns = cluster.getColSpan(); + const unsigned mask = cluster.getPattern(); + if (mask == o2::iotof::Cluster::InvalidPatternID || rows == 0 || columns == 0 || rows * columns > 16 || cluster.getRow() + rows > frame.rowX.size() || cluster.getCol() + columns > frame.columnZ.size()) { + ++skipped.pattern; + continue; + } + double x = 0.; + double z = 0.; + int pixels = 0; + for (unsigned bit = 0; bit < rows * columns; ++bit) { + if ((mask & (1U << bit)) != 0U) { + x += frame.rowX[cluster.getRow() + (bit / columns)]; + z += frame.columnZ[cluster.getCol() + (bit % columns)]; + ++pixels; + } + } + if (pixels == 0) { + ++skipped.pattern; + continue; + } + // Its time from the timeframe's start, the bunch crossings' difference + // taken first; the box the crossing that ends there, in the timeframe. + const std::int64_t timePS = psOfBC(static_cast(cluster.getBc()) - firstBC) + std::llround(static_cast(fineNS) * 1000.); + std::int64_t start = timePS - widthPS; + if (start < 0 || timePS > durationPS) { + ++skipped.clamped; + start = std::clamp(start, 0, durationPS - widthPS); + } + result.push_back({ + .chipID = static_cast(detectors::TRKFT3TOF::kFirstTOFSensor + static_cast(chip)), + .xLocal = static_cast(x / pixels), + .yLocal = static_cast(z / pixels), + .sigmaXLocal = frame.sigmaX, + .sigmaYLocal = frame.sigmaZ, + .timePS = static_cast(start), + .widthPS = static_cast(widthPS), + .rowSpan = static_cast(rows), + .colSpan = static_cast(columns), + }); + kept.push_back(static_cast(index)); + } + // In box-start order, as the measurement producer takes a layer timed per + // hit (MeasurementProducer.h): its stable counting sort keeps every + // bucket's rows in it. The clusters come in the clusterer's order. + std::vector order(result.size()); + std::iota(order.begin(), order.end(), 0U); + std::ranges::stable_sort(order, {}, [&](std::uint32_t i) { return result[i].timePS; }); + std::vector sorted(result.size()); + std::vector sortedKept(kept.size()); + for (std::size_t i = 0; i < order.size(); ++i) { + sorted[i] = result[order[i]]; + sortedKept[i] = kept[order[i]]; + } + kept = std::move(sortedKept); + return sorted; +} + +std::vector trktofFrameTiming(std::span trk) +{ + using Layout = detectors::TRKFT3TOF; + if (trk.size() != static_cast(Detector::nLayers)) { + throw std::invalid_argument(std::format("TRKFT3TOF: {} TRKFT3 layers' frames, the layout has {}", trk.size(), Detector::nLayers)); + } + std::vector frames(static_cast(Detector::nLayers), FrameTiming{.lengthBC = 1, .firstStartBC = 0}); + for (std::size_t layer = 0; layer < trk.size(); ++layer) { + frames[detectors::trkft3tof::fromTRKFT3(static_cast(layer))] = trk[layer]; + } + return frames; +} + +std::vector trktofMeasurementDepthsCM(std::span trk) +{ + using Layout = detectors::TRKFT3TOF; + std::vector depths(static_cast(Detector::nLayers), 0.); + for (std::size_t layer = 0; layer < trk.size() && std::cmp_less(layer, Detector::nLayers); ++layer) { + depths[detectors::trkft3tof::fromTRKFT3(static_cast(layer))] = trk[layer]; + } + return depths; +} + +} // namespace o2::gtrk::alice + +namespace o2::gtrk::workflow +{ + +template <> +o2::framework::DataProcessorSpec getClusterConverterSpec(const o2::framework::ConfigContext& /*context*/, bool useMC) +{ + return trkClusterConverterSpec(useMC); +} + +template o2::framework::DataProcessorSpec getMeasurementProducerSpec(); + +} // namespace o2::gtrk::workflow diff --git a/Detectors/GenericTracking/workflow-trk/src/TrackerTRKFT3TOF.cxx b/Detectors/GenericTracking/workflow-trk/src/TrackerTRKFT3TOF.cxx new file mode 100644 index 0000000000000..8bbacc54375ff --- /dev/null +++ b/Detectors/GenericTracking/workflow-trk/src/TrackerTRKFT3TOF.cxx @@ -0,0 +1,25 @@ +// Copyright 2019-2020 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 TrackerTRKFT3TOF.cxx +/// \brief TRKFT3TOF's tracking device (TrackerDevice.h): one unit per detector, +/// each instantiating the tracker. + +#include "GenericTracking/Detectors/TRKFT3TOF.h" +#include "GenericTracking/Workflow/TrackerDevice.h" +#include "GenericTracking/WorkflowTRK/ConditionsTRK.h" + +namespace o2::gtrk +{ + +template o2::framework::DataProcessorSpec workflow::getTrackerSpec(bool withVertices); + +} // namespace o2::gtrk diff --git a/Detectors/GenericTracking/workflow-trk/src/TrkClusterConverter.h b/Detectors/GenericTracking/workflow-trk/src/TrkClusterConverter.h new file mode 100644 index 0000000000000..7f2eeeac9ff31 --- /dev/null +++ b/Detectors/GenericTracking/workflow-trk/src/TrkClusterConverter.h @@ -0,0 +1,229 @@ +// Copyright 2019-2020 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 TrkClusterConverter.h +/// \brief ALICE 3's cluster converter, TRKFT3's and TRKFT3TOF's (TRK.cxx, +/// TRKTOF.cxx): the library's own, no installed header. + +#ifndef GTRK_WORKFLOWTRK_TRKCLUSTERCONVERTER_H_ +#define GTRK_WORKFLOWTRK_TRKCLUSTERCONVERTER_H_ + +#include "GenericTracking/Base/LayerSpec.h" +#include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" +#include "GenericTracking/Clustering/Cluster.h" +#include "GenericTracking/Workflow/DataSpecs.h" +#include "GenericTracking/WorkflowTRK/ConditionsTRK.h" +#include "GenericTracking/WorkflowTRK/TRK.h" +#include "GenericTracking/WorkflowTRK/TRKTOF.h" + +#include "DataFormatsIOTOF/Cluster.h" +#include "DataFormatsTRKFT3/Cluster.h" +#include "DataFormatsTRKFT3/ROFRecord.h" +#include "DetectorsBase/GRPGeomHelper.h" +#include "DetectorsRaw/HBFUtils.h" +#include "Framework/ConcreteDataMatcher.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/Logger.h" +#include "Framework/Task.h" +#include "Framework/TimingInfo.h" +#include "Headers/DataHeader.h" +#include "IOTOFBase/GeometryTGeo.h" +#include "SimulationDataFormat/ConstMCTruthContainer.h" +#include "SimulationDataFormat/MCCompLabel.h" +#include "SimulationDataFormat/MCTruthContainer.h" +#include "TRKBase/GeometryTGeo.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace o2::gtrk::workflow +{ + +/// ALICE 3's TRK and FT3 clusters, one stream per barrel layer and one per +/// disc as O2's cluster readers publish them (TRK/COMPCLUSTERS/, +/// FT3/COMPCLUSTERS/ and the rest), turned into GTRK/TRKCLUSTERS and +/// GTRK/TRKCLUSMCTR: each layer's +/// stream converted with its own readout frames, each cluster with its +/// position and errors from the topology dictionaries, CCDB conditions, +/// then the layers +/// concatenated in order, barrel first, so a measurement's cluster index is +/// its position in that concatenation and the labels follow it. For +/// TRKFT3TOF the TOF's clusters (TF3/CLUSTERS/0, TRKTOF.h's `tofClusters`) +/// follow the TRK's, with their labels. +template +class TrkClusterConverterTask : public o2::framework::Task +{ + public: + static constexpr bool kTOF = std::same_as; + /// TRK's and FT3's streams, TRKFT3's layers. + static constexpr int kLayers = Detector::nLayers; + static constexpr int kBarrelLayers = Detector::nBarrelLayers; + + /// TRKFT3's layer \a layer's stream: TRK's barrel layer, or FT3's disc after them. + [[nodiscard]] static o2::header::DataOrigin originOf(int layer) { return layer < kBarrelLayers ? o2::header::DataOrigin{"TRK"} : o2::header::DataOrigin{"FT3"}; } + [[nodiscard]] static o2::header::DataHeader::SubSpecificationType subspecOf(int layer) { return static_cast(layer < kBarrelLayers ? layer : layer - kBarrelLayers); } + + TrkClusterConverterTask(bool useMC, TrkDictionaryConditions dictionaries, std::shared_ptr geometryRequest) + : mUseMC(useMC), mDictionaries(dictionaries), mGeometryRequest(std::move(geometryRequest)) {} + + void init(o2::framework::InitContext& /*ic*/) final { o2::base::GRPGeomHelper::instance().setRequest(mGeometryRequest); } + + void finaliseCCDB(o2::framework::ConcreteDataMatcher& matcher, void* obj) final + { + if (!o2::base::GRPGeomHelper::instance().finaliseCCDB(matcher, obj)) { + mDictionaries.finaliseCCDB(matcher, obj); + } + } + + void run(o2::framework::ProcessingContext& pc) final + { + o2::base::GRPGeomHelper::instance().checkUpdates(pc); + // Dictionary coordinates use the VD segmentation's petal count, which + // GeometryTGeo derives from the loaded geometry in this device's process. + o2::trk::GeometryTGeo::Instance(); + TrkDictionaryConditions::checkUpdates(pc); + const auto& timing = pc.services().get(); + std::vector clusters; + o2::dataformats::MCTruthContainer labels; + for (int layer = 0; layer < kLayers; ++layer) { + const auto patterns = pc.inputs().get>(std::format("patterns_{}", layer)); + const auto rofs = pc.inputs().get>(std::format("rofs_{}", layer)); + if (rofs.empty()) { + continue; + } + // The timeframe's first orbit as DPL announces it, held to the one the + // frames imply, as for the ITS. + const auto implied = o2::raw::HBFUtils::Instance().getFirstIRofTF(rofs.front().getBCData()).orbit; + if (implied != timing.firstTForbit) { + LOGP(fatal, "TRKFT3 layer {}: the readout frames belong to the timeframe starting at orbit {}, DPL says {}", layer, implied, timing.firstTForbit); + } + const std::span patternBytes{patterns.data(), patterns.size()}; + const auto local = [&]() { + if (layer < kBarrelLayers) { + const auto compact = pc.inputs().get>(std::format("compclusters_{}", layer)); + return alice::trkLocalClusters(std::span{compact.data(), compact.size()}, patternBytes, *mDictionaries.trk()); + } + const auto compact = pc.inputs().get>(std::format("compclusters_{}", layer)); + return alice::ft3LocalClusters(std::span{compact.data(), compact.size()}, patternBytes, *mDictionaries.ft3()); + }(); + const std::span frames{rofs.data(), rofs.size()}; + const auto converted = alice::toClusters(local, frames, alice::readoutFrames(frames), timing.firstTForbit); + clusters.insert(clusters.end(), converted.begin(), converted.end()); + if (mUseMC) { + const auto layerLabels = pc.inputs().get*>(std::format("labels_{}", layer)); + if (layerLabels->getIndexedSize() != converted.size()) { + LOGP(fatal, "TRKFT3 layer {}: {} labelled clusters for {} clusters", layer, layerLabels->getIndexedSize(), converted.size()); + } + labels.mergeAtBack(*layerLabels); + } + } + if constexpr (kTOF) { + appendTOF(pc, timing.firstTForbit, clusters, labels); + } + LOGP(info, "{}: {} clusters on {} layers for the timeframe at orbit {}", Det::name, clusters.size(), Detector::nLayers, timing.firstTForbit); + pc.outputs().snapshot(o2::framework::Output{gDataOrigin, description(kClusters), 0}, clusters); + if (mUseMC) { + auto& flat = pc.outputs().make>(o2::framework::Output{gDataOrigin, description(kClustersMCTruth), 0}); + labels.flatten_to(flat); + } + } + + /// The converter's inputs, outputs and device (`getClusterConverterSpec`). + [[nodiscard]] static o2::framework::DataProcessorSpec spec(bool useMC) + { + using namespace o2::framework; + std::vector inputs; + std::vector outputs{OutputSpec{gDataOrigin, description(kClusters), 0, Lifetime::Timeframe}}; + for (int layer = 0; layer < kLayers; ++layer) { + const auto origin = originOf(layer); + const auto subspec = subspecOf(layer); + inputs.emplace_back(std::format("compclusters_{}", layer), origin, "COMPCLUSTERS", subspec, Lifetime::Timeframe); + inputs.emplace_back(std::format("patterns_{}", layer), origin, "PATTERNS", subspec, Lifetime::Timeframe); + inputs.emplace_back(std::format("rofs_{}", layer), origin, "CLUSTERSROF", subspec, Lifetime::Timeframe); + if (useMC) { + inputs.emplace_back(std::format("labels_{}", layer), origin, "CLUSTERSMCTR", subspec, Lifetime::Timeframe); + } + } + if constexpr (kTOF) { + inputs.emplace_back("tofclusters", o2::header::gDataOriginTF3, "CLUSTERS", 0, Lifetime::Timeframe); + if (useMC) { + inputs.emplace_back("toflabels", o2::header::gDataOriginTF3, "CLUSTERSMCTR", 0, Lifetime::Timeframe); + } + } + if (useMC) { + outputs.emplace_back(gDataOrigin, description(kClustersMCTruth), 0, Lifetime::Timeframe); + } + const TrkDictionaryConditions dictionaries(inputs); + auto geometryRequest = std::make_shared(false, false, false, false, false, o2::base::GRPGeomRequest::Aligned, inputs); + return DataProcessorSpec{ + .name = deviceName("cluster-converter"), + .inputs = inputs, + .outputs = outputs, + .algorithm = AlgorithmSpec{adaptFromTask(useMC, dictionaries, geometryRequest)}, + .options = Options{}, + }; + } + + private: + /// The TOF's clusters after the TRK's, and their labels: those + /// `tofClusters` keeps, the others counted in one warning per timeframe. + void appendTOF(o2::framework::ProcessingContext& pc, std::uint32_t tfFirstOrbit, std::vector& clusters, o2::dataformats::MCTruthContainer& labels) + { + if (!mTofFrame) { + auto& geometry = *o2::iotof::GeometryTGeo::Instance(); + mTofFrame = alice::TofPixelFrame::build(geometry); + } + const auto tof = pc.inputs().get>("tofclusters"); + std::vector kept; + alice::TofSkipped skipped; + const auto converted = alice::tofClusters(std::span{tof.data(), tof.size()}, *mTofFrame, tfFirstOrbit, o2::raw::HBFUtils::Instance().getNOrbitsPerTF(), kept, skipped); + if (skipped.total() != 0 || skipped.clamped != 0) { + LOGP(warn, "TRKFT3TOF: of {} TOF clusters {} left out (no chip {}, time {}, pattern {}), {} moved into the timeframe", tof.size(), skipped.total(), skipped.chip, skipped.time, skipped.pattern, skipped.clamped); + } + if (mUseMC) { + const auto tofLabels = pc.inputs().get*>("toflabels"); + if (tofLabels->getIndexedSize() != tof.size()) { + LOGP(fatal, "TRKFT3TOF: {} labelled TOF clusters for {} clusters", tofLabels->getIndexedSize(), tof.size()); + } + const auto first = clusters.size(); + for (std::size_t i = 0; i < kept.size(); ++i) { + const auto own = tofLabels->getLabels(kept[i]); + labels.addElements(first + i, gsl::span{own.data(), own.size()}); + } + } + clusters.insert(clusters.end(), converted.begin(), converted.end()); + } + + bool mUseMC; + TrkDictionaryConditions mDictionaries; + std::shared_ptr mGeometryRequest; + std::optional mTofFrame; ///< TRKFT3TOF's, from the first timeframe's geometry +}; + +/// `getClusterConverterSpec` of TRKFT3 and TRKFT3TOF. +template +[[nodiscard]] o2::framework::DataProcessorSpec trkClusterConverterSpec(bool useMC) +{ + return TrkClusterConverterTask::spec(useMC); +} + +} // namespace o2::gtrk::workflow + +#endif // GTRK_WORKFLOWTRK_TRKCLUSTERCONVERTER_H_ diff --git a/Detectors/GenericTracking/workflow-trk/src/gtrk-trk-reco-workflow.cxx b/Detectors/GenericTracking/workflow-trk/src/gtrk-trk-reco-workflow.cxx index 296c2055bdc83..48b8cb91111ca 100644 --- a/Detectors/GenericTracking/workflow-trk/src/gtrk-trk-reco-workflow.cxx +++ b/Detectors/GenericTracking/workflow-trk/src/gtrk-trk-reco-workflow.cxx @@ -18,6 +18,11 @@ /// tracker of the TRKFT3 layout, the topology dictionaries as CCDB /// conditions. With `--vertices-from-upstream` the tracker takes the native /// vertex seeds (GTRK/TRKVERTICES) from the workflow before it in the pipe. +/// With `--tof-layers` the layout is TRKFT3TOF (Detectors/TRKFT3TOF.h): the +/// IOTOF's clusters too (O2's TF3 cluster reader, unless +/// `--clusters-from-upstream`), found, owned and fitted by the tracking as +/// the TRK's, the material LUT `TRK/Param/MatLUTTOF`. The products are the +/// same: GTRK/TRKTRACKS, whose cluster references then hold TOF rows. /// No adaptor: ALICE 3 has no O2 track format yet. #include "GenericTracking/Workflow/RecoWorkflow.h" @@ -33,11 +38,17 @@ using namespace o2::framework; void customize(std::vector& policies) { o2::raw::HBFUtilsInitializer::addNewTimeSliceCallback(policies); } // NOLINTNEXTLINE(misc-use-internal-linkage) -void customize(std::vector& workflowOptions) { o2::gtrk::workflow::addRecoOptions(workflowOptions); } +void customize(std::vector& workflowOptions) +{ + o2::gtrk::workflow::addRecoOptions(workflowOptions); + workflowOptions.push_back(ConfigParamSpec{"tof-layers", VariantType::Bool, false, {"track with the IOTOF's layers (the TRKFT3TOF layout)"}}); +} #include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" #include "Framework/runDataProcessing.h" // IWYU pragma: keep +#include "IOTOFWorkflow/ClusterReaderSpec.h" #include "TRKWorkflow/ClusterReaderSpec.h" #include @@ -47,7 +58,9 @@ WorkflowSpec defineDataProcessing(const ConfigContext& context) o2::conf::ConfigurableParam::updateFromString(context.options().get("configKeyValues")); const bool useMC = !context.options().get("disable-mc"); - auto specs = o2::gtrk::workflow::trackingChain(context, {o2::trk::getTRKClusterReaderSpec(useMC), o2::trk::getFT3ClusterReaderSpec(useMC)}); + auto specs = context.options().get("tof-layers") + ? o2::gtrk::workflow::trackingChain(context, {o2::trk::getTRKClusterReaderSpec(useMC), o2::trk::getFT3ClusterReaderSpec(useMC), o2::iotof::getIOTOFClusterReaderSpec(useMC)}) + : o2::gtrk::workflow::trackingChain(context, {o2::trk::getTRKClusterReaderSpec(useMC), o2::trk::getFT3ClusterReaderSpec(useMC)}); const o2::raw::HBFUtilsInitializer hbfIni(context, specs); diff --git a/Detectors/GenericTracking/workflow-trk/test/CMakeLists.txt b/Detectors/GenericTracking/workflow-trk/test/CMakeLists.txt index c95b4b322342f..4fcd4e074af0b 100644 --- a/Detectors/GenericTracking/workflow-trk/test/CMakeLists.txt +++ b/Detectors/GenericTracking/workflow-trk/test/CMakeLists.txt @@ -19,3 +19,4 @@ function(gtrk_workflow_trk_test name source) endfunction() gtrk_workflow_trk_test(trk testTrkChainPulls.cxx O2::MathUtils) +gtrk_workflow_trk_test(trk-tof testTrkTof.cxx O2::DataFormatsIOTOF O2::CommonConstants) diff --git a/Detectors/GenericTracking/workflow-trk/test/testTrkTof.cxx b/Detectors/GenericTracking/workflow-trk/test/testTrkTof.cxx new file mode 100644 index 0000000000000..cc856d718f662 --- /dev/null +++ b/Detectors/GenericTracking/workflow-trk/test/testTrkTof.cxx @@ -0,0 +1,274 @@ +// Copyright 2019-2020 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 testTrkTof.cxx +/// \brief TRKFT3TOF, ALICE 3's tracker with its TOF layers, against TRKFT3: +/// layer mapping, native settings and grid, frame times, measurement +/// depths and IOTOF cluster conversion (WorkflowTRK/TRKTOF.h). + +#define BOOST_TEST_DYN_LINK +#define BOOST_TEST_MODULE Test GTRK TRKTOF +#include "GenericTracking/Base/Geometry.h" +#include "GenericTracking/Base/LayerSpec.h" +#include "GenericTracking/Base/TimeEstPS.h" +#include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" +#include "GenericTracking/Alice/Placement.h" +#include "GenericTracking/Workflow/BeamLine.h" +#include "GenericTracking/Workflow/GridConfig.h" +#include "GenericTracking/Workflow/RecoParam.h" +#include "GenericTracking/WorkflowTRK/TRKTOF.h" + +#include "CommonConstants/LHCConstants.h" +#include "DataFormatsIOTOF/Cluster.h" +#include "DetectorsBase/GeometryManager.h" +#include "DetectorsBase/Propagator.h" + +#include "UniformMaterial.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +using namespace o2::gtrk; +using Base = detectors::TRKFT3; +using Tof = detectors::TRKFT3TOF; +constexpr int kBaseLayers = Detector::nLayers; + +[[nodiscard]] const PlacedLayerSpec& layerSpec(auto layout, int layer) +{ + using L = decltype(layout); + return layer < Detector::nBarrelLayers ? L::barrelLayers[static_cast(layer)] : L::discLayers[static_cast(layer - Detector::nBarrelLayers)]; +} + +} // namespace + +/// TRKFT3's layers in their order with the two TOF layers among them: the +/// iTOF between ML 6 and 7, the oTOF after the OT, the discs after it; the +/// same sensors, overlaps and links, and the TOF layers inactive. +BOOST_AUTO_TEST_CASE(TRKFT3TOFIsTRKFT3WithTheTOFLayers) +{ + BOOST_TEST(Detector::nLayers == kBaseLayers + 2); + BOOST_TEST(Detector::nBarrelLayers == Detector::nBarrelLayers + 2); + BOOST_TEST(Detector::inactiveLayers == (std::uint64_t{1} << Tof::kInnerTOFLayer | std::uint64_t{1} << Tof::kOuterTOFLayer)); + BOOST_TEST(Detector::inactiveLayers == 0U); + // The TOF's clusters carry their own boxes; TRKFT3's are frame records. + BOOST_TEST(Detector::hitTimedLayers == Detector::inactiveLayers); + BOOST_TEST(Detector::hitTimedLayers == 0U); + BOOST_TEST(Tof::kFirstTOFSensor == Base::nSensors); + std::vector taken(static_cast(Detector::nLayers), false); + for (int layer = 0; layer < kBaseLayers; ++layer) { + const auto to = detectors::trkft3tof::fromTRKFT3(static_cast(layer)); + BOOST_TEST_CONTEXT("TRKFT3 layer " << layer << " -> " << static_cast(to)) + { + BOOST_TEST(!Detector::isInactiveLayer(to)); + BOOST_TEST(!taken[to]); + taken[to] = true; + BOOST_TEST(Detector::isBarrelLayer(to) == Detector::isBarrelLayer(static_cast(layer))); + BOOST_TEST(layerSpec(Tof{}, to).sensorCount == layerSpec(Base{}, layer).sensorCount); + BOOST_TEST(layerSpec(Tof{}, to).sensor.halfX == layerSpec(Base{}, layer).sensor.halfX); + BOOST_TEST(((Tof::overlapLayers >> to) & 1U) == ((Base::overlapLayers >> layer) & 1U)); + } + } + BOOST_TEST(!taken[Tof::kInnerTOFLayer]); + BOOST_TEST(!taken[Tof::kOuterTOFLayer]); + BOOST_TEST(((Tof::overlapLayers >> Tof::kInnerTOFLayer) & 1U) == 0U); + // Every TRKFT3 link, renumbered, with its source range. + for (const auto& link : Base::layerLinks) { + const auto found = std::ranges::find_if(Tof::layerLinks, [&](const LayerLink& other) { return other.from == detectors::trkft3tof::fromTRKFT3(link.from) && other.to == detectors::trkft3tof::fromTRKFT3(link.to); }); + BOOST_TEST_CONTEXT("link " << static_cast(link.from) << " -> " << static_cast(link.to)) + { + BOOST_REQUIRE(found != Tof::layerLinks.end()); + BOOST_TEST(found->sourceMin == link.sourceMin); + BOOST_TEST(found->sourceMax == link.sourceMax); + } + } + // ML 6 -> ML 7 stays direct, beside ML 6 -> iTOF -> ML 7. + const auto has = [](LayerID from, LayerID to) { return std::ranges::any_of(Tof::layerLinks, [&](const LayerLink& link) { return link.from == from && link.to == to; }); }; + BOOST_TEST(has(6, detectors::trkft3tof::fromTRKFT3(7))); + BOOST_TEST(has(6, Tof::kInnerTOFLayer)); + BOOST_TEST(has(Tof::kInnerTOFLayer, detectors::trkft3tof::fromTRKFT3(7))); +} + +/// A TOF configuration can be set independently of the TRK configuration. +BOOST_AUTO_TEST_CASE(TheTofScheduleUsesItsOwnKeys) +{ + const auto trk = recoParam().iterationMinPtGeV; + o2::conf::ConfigurableParam::updateFromString("GTRKRecoTRKTOF.iterationMinPtGeV=[0.5];GTRKRecoTRKTOF.iterationLayerMask=[248]"); + const auto& tof = recoParam(); + BOOST_TEST(tof.iterationMinPtGeV == (std::vector{0.5}), boost::test_tools::per_element()); + BOOST_TEST(tof.iterationLayerMask == (std::vector{248}), boost::test_tools::per_element()); + BOOST_TEST(recoParam().iterationMinPtGeV == trk, boost::test_tools::per_element()); +} + +/// The default mask admits iTOF links and keeps oTOF for the follower. +BOOST_AUTO_TEST_CASE(TheDefaultMaskKeepsOuterTofOutOfSeeding) +{ + RecoSettings tof; + tof.iterationMinPtGeV = {0.1, 0.2}; + o2::base::Propagator::Instance(true); + for (int iteration = 0; iteration < workflow::iterationCount(tof); ++iteration) { + const auto links = takenLinks(workflow::iterationSettings(tof, iteration)); + bool innerSeeded = false; + bool outerSeeded = false; + for (std::size_t i = 0; i < links.size(); ++i) { + const auto& link = Tof::layerLinks[i]; + innerSeeded |= links[i] && (link.from == Tof::kInnerTOFLayer || link.to == Tof::kInnerTOFLayer); + outerSeeded |= links[i] && (link.from == Tof::kOuterTOFLayer || link.to == Tof::kOuterTOFLayer); + } + BOOST_TEST(innerSeeded); + BOOST_TEST(!outerSeeded); + } +} + +/// TRKFT3TOF's frames and depths are TRKFT3's on its layers; the TOF's a +/// bunch crossing from BC 0 at depth 0. +BOOST_AUTO_TEST_CASE(TheFramesAndDepthsAreTRKFT3sOnItsLayers) +{ + std::vector frames; + std::vector depths; + for (int layer = 0; layer < kBaseLayers; ++layer) { + frames.push_back({.lengthBC = 18 + layer, .firstStartBC = layer % 3}); + depths.push_back(-0.001 * (layer + 1)); + } + const auto tofFrames = alice::trktofFrameTiming(frames); + const auto tofDepths = alice::trktofMeasurementDepthsCM(depths); + BOOST_REQUIRE(tofFrames.size() == static_cast(Detector::nLayers)); + BOOST_REQUIRE(tofDepths.size() == static_cast(Detector::nLayers)); + for (int layer = 0; layer < kBaseLayers; ++layer) { + const auto to = detectors::trkft3tof::fromTRKFT3(static_cast(layer)); + BOOST_TEST(tofFrames[to].lengthBC == frames[static_cast(layer)].lengthBC); + BOOST_TEST(tofFrames[to].firstStartBC == frames[static_cast(layer)].firstStartBC); + BOOST_TEST(tofDepths[to] == depths[static_cast(layer)]); + } + for (const auto layer : {Tof::kInnerTOFLayer, Tof::kOuterTOFLayer}) { + BOOST_TEST(tofFrames[layer].lengthBC == 1); + BOOST_TEST(tofFrames[layer].firstStartBC == 0); + BOOST_TEST(tofDepths[layer] == 0.); + } + BOOST_CHECK_THROW((void)alice::trktofFrameTiming(std::span{frames}.first(3)), std::invalid_argument); +} + +/// The native grid and tracker accept pT floors through the longest TOF +/// chain. The legacy width remains usable with the shorter TRK layout. +BOOST_AUTO_TEST_CASE(TheNativeGridAndFloorsCoverLongTofChains) +{ + static_assert(maxChainLayers == 15U && maxChainLayers == 17U); + RecoSettings settings; + settings.iterationMinPtGeV = {0.5, 0.3}; + settings.iterationClusterMinPtGeV.assign(2U * RecoSettings::kClusterSlots, 0.); + settings.iterationClusterMinPtGeV[17] = 0.25; + settings.iterationClusterMinPtGeV[RecoSettings::kClusterSlots + 16] = 0.5; + o2::base::Propagator::Instance(true)->setNominalBz(20.F); + const auto first = workflow::iterationSettings(settings, 0); + const auto second = workflow::iterationSettings(settings, 1); + BOOST_TEST(first.minPtGeVByClusters[17] == 0.25); + BOOST_TEST(second.minPtGeVByClusters[16] == 0.5); + BOOST_TEST(second.minPtGeVByClusters[17] == 0.); + + const char* file = std::getenv("GTRK_ALICE3_GEOMETRY"); + if (file == nullptr) { + BOOST_TEST_MESSAGE("GTRK_ALICE3_GEOMETRY unset: the geometry-dependent checks are skipped"); + return; + } + o2::base::GeometryManager::loadGeometry(file); + const auto tofGeometry = std::make_unique>(alice::placeChecked()); + const std::vector trkFrames(static_cast(kBaseLayers), FrameTiming{.lengthBC = 81, .firstStartBC = 0}); + const auto tofFrames = alice::trktofFrameTiming(trkFrames); + const auto beam = workflow::nominalBeamLine(); + const auto grid = std::make_unique>(workflow::makeGridGeometry(settings, beam, tofFrames, 32)); + BOOST_TEST(!grid->overflows()); + BOOST_TEST(grid->axes(Tof::kInnerTOFLayer).nPhi > 0); + const auto scattering = scatteringTable(uniformLayerMaterial(0.)); + BOOST_TEST(iterationParameters(first, VertexConstraint{}, scattering).minPtByClusters[17] == 0.25F); + BOOST_TEST(iterationParameters(second, VertexConstraint{}, scattering).minPtByClusters[16] == 0.5F); + + settings.iterationClusterMinPtGeV.assign(2U * RecoSettings::kLegacyClusterSlots, 0.); + settings.iterationClusterMinPtGeV[RecoSettings::kLegacyClusterSlots + 7] = 0.5; + BOOST_TEST(workflow::iterationSettings(settings, 1).minPtGeVByClusters[7] == 0.5); + BOOST_CHECK_THROW(workflow::makeGridGeometry(settings, beam, tofFrames, 32), std::invalid_argument); + const auto trkGeometry = std::make_unique>(alice::placeChecked()); + const auto trkGrid = std::make_unique>(workflow::makeGridGeometry(settings, beam, trkFrames, 32)); + BOOST_TEST(!trkGrid->overflows()); +} + +/// An IOTOF cluster as ours: its fired pixels' mean centre in its chip's +/// frame, pitch^2/12 errors, the sensor after TRKFT3's, the box of the bunch +/// crossing ending at its time; one on no chip, outside its crossing or +/// without a usable pattern left out and counted; a box past the +/// timeframe's start or end moved in and counted. +BOOST_AUTO_TEST_CASE(ATOFClusterIsItsPixelsAndTheCrossingEndingAtItsTime) +{ + alice::TofPixelFrame frame; + for (int row = 0; row < 8; ++row) { + frame.rowX.push_back(0.01F * static_cast(row) - 0.035F); + } + for (int column = 0; column < 6; ++column) { + frame.columnZ.push_back(0.025F * static_cast(column) - 0.0625F); + } + frame.sigmaX = 0.01F / std::sqrt(12.F); + frame.sigmaZ = 0.025F / std::sqrt(12.F); + frame.chips = 4; + constexpr std::uint32_t kFirstOrbit = 5; + constexpr int kOrbits = 2; + const std::uint64_t firstBC = std::uint64_t{kFirstOrbit} * o2::constants::lhc::LHCMaxBunches; + using o2::iotof::Cluster; + std::vector clusters{ + // one pixel, at row 2, column 3, 100 BC into the timeframe, 7.5 ns into its crossing + Cluster(2, 3, 1, 1, 0b1, 0, 1, 0.F, firstBC + 100, 7.5F), + // two pixels side by side across the rows (row-major 2 x 1: bits 0 and 1) + Cluster(4, 1, 2, 1, 0b11, 0, 3, 0.F, firstBC + 2000, 0.F), + Cluster(0, 0, 1, 1, 0b1, 0, 4, 0.F, firstBC + 10, 1.F), // no such chip + Cluster(0, 0, 1, 1, 0b1, 0, 0, 0.F, firstBC + 10, 30.F), // outside its crossing + Cluster(0, 0, 1, 1, 0, 0, 0, 0.F, firstBC + 10, 1.F), // no pixel fired + Cluster(7, 5, 2, 1, 0b11, 0, 0, 0.F, firstBC + 10, 1.F), // a pixel past the last row + Cluster(0, 0, 1, 1, 0b1, 0, 2, 0.F, firstBC, 1.F), // a box from before the timeframe + }; + std::vector kept; + alice::TofSkipped skipped; + const auto ours = alice::tofClusters(clusters, frame, kFirstOrbit, kOrbits, kept, skipped); + BOOST_REQUIRE(ours.size() == 3U); + // In box-start order: the box moved to the timeframe's start first. + BOOST_TEST(kept == (std::vector{6, 0, 1}), boost::test_tools::per_element()); + BOOST_TEST(skipped.chip == 1U); + BOOST_TEST(skipped.time == 1U); + BOOST_TEST(skipped.pattern == 2U); + BOOST_TEST(skipped.clamped == 1U); + + BOOST_TEST(ours[1].chipID == static_cast(Tof::kFirstTOFSensor + 1)); + BOOST_TEST(ours[1].xLocal == frame.rowX[2]); + BOOST_TEST(ours[1].yLocal == frame.columnZ[3]); + BOOST_TEST(ours[1].sigmaXLocal == frame.sigmaX); + BOOST_TEST(ours[1].sigmaYLocal == frame.sigmaZ); + const std::int64_t t0 = psOfBC(100) + 7500; + BOOST_TEST(ours[1].timePS == static_cast(t0 - psOfBC(1))); + BOOST_TEST(ours[1].widthPS == static_cast(psOfBC(1))); + BOOST_TEST(ours[1].rowSpan == 1U); + BOOST_TEST(ours[1].colSpan == 1U); + + BOOST_TEST(ours[2].chipID == static_cast(Tof::kFirstTOFSensor + 3)); + BOOST_TEST(ours[2].xLocal == 0.5F * (frame.rowX[4] + frame.rowX[5]), boost::test_tools::tolerance(1.e-6F)); + BOOST_TEST(ours[2].yLocal == frame.columnZ[1]); + BOOST_TEST(ours[2].timePS == static_cast(psOfBC(2000) - psOfBC(1))); + BOOST_TEST(ours[2].rowSpan == 2U); + + // [t - 1 BC, t] at t = 1 ns reaches before the timeframe: moved to its start. + BOOST_TEST(ours[0].timePS == 0U); + BOOST_TEST(ours[0].widthPS == static_cast(psOfBC(1))); +} diff --git a/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/GridConfig.h b/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/GridConfig.h index b80ad5a2b55d4..7a9411bee5485 100644 --- a/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/GridConfig.h +++ b/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/GridConfig.h @@ -186,7 +186,10 @@ inline void checkRecoParam(const RecoSettings& param) check("iterationBeamConstraint", param.iterationBeamConstraint.size(), 1U); check("iterationFollowEarlier", param.iterationFollowEarlier.size(), 1U); check("iterationSharedGraph", param.iterationSharedGraph.size(), 1U); - check("iterationClusterMinPtGeV", param.iterationClusterMinPtGeV.size(), static_cast(RecoSettings::kClusterSlots)); + const auto floors = param.iterationClusterMinPtGeV.size(); + if (floors != 0U && floors != count * RecoSettings::kClusterSlots && floors != count * RecoSettings::kLegacyClusterSlots) { + throw std::invalid_argument(std::format("GTRKReco.iterationClusterMinPtGeV has {} entries; {} iterations want {} or {} per iteration, or none", floors, count, RecoSettings::kLegacyClusterSlots, RecoSettings::kClusterSlots)); + } return static_cast(count); } @@ -215,8 +218,9 @@ inline void checkRecoParam(const RecoSettings& param) static_assert(RecoSettings::kClusterSlots == IterationSettings::kClusterSlots); std::array floors{}; if (!param.iterationClusterMinPtGeV.empty()) { - for (std::size_t count = 0; count < floors.size(); ++count) { - floors[count] = param.iterationClusterMinPtGeV[(index * IterationSettings::kClusterSlots) + count]; + const auto slots = param.iterationClusterMinPtGeV.size() / param.iterationMinPtGeV.size(); + for (std::size_t count = 0; count < slots; ++count) { + floors[count] = param.iterationClusterMinPtGeV[(index * slots) + count]; } } const bool follow = flag(param.iterationFollow, defaults.follow); @@ -384,10 +388,11 @@ template if (frames.size() != static_cast(Detector::nLayers)) { throw std::invalid_argument(std::format("{}'s grid follows its {} layers' readout frames, and {} were given", Det::name, Detector::nLayers, frames.size())); } - // A pT floor per cluster count has a slot for every chain the layout can - // hold, or none would apply to the longest silently. - if (!param.iterationClusterMinPtGeV.empty() && maxChainLayers + 1U > IterationSettings::kClusterSlots) { - throw std::invalid_argument(std::format("GTRKReco.iterationClusterMinPtGeV has {} slots per iteration, and {}'s chains reach {} clusters", IterationSettings::kClusterSlots, Det::name, maxChainLayers)); + if (!param.iterationClusterMinPtGeV.empty()) { + const auto slots = param.iterationClusterMinPtGeV.size() / param.iterationMinPtGeV.size(); + if (slots <= maxChainLayers) { + throw std::invalid_argument(std::format("{}.iterationClusterMinPtGeV has {} slots per iteration, and {}'s chains reach {} clusters", RecoParamOf::type::Instance().getName(), slots, Det::name, maxChainLayers)); + } } const auto windows = gridLayerWindows(iterations, beamSpotConstraint(beam, param)); GridGeometry geometry{timeframeDurationPS(orbitsPerTimeframe), gridParams(param, frames), windows}; diff --git a/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/MaterialLUT.h b/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/MaterialLUT.h index 97f4989e23599..d11ad41112afe 100644 --- a/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/MaterialLUT.h +++ b/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/MaterialLUT.h @@ -17,6 +17,7 @@ /// | ITS | `GLO/Param/MatLUT` (O2's, or `o2-gtrk-build-matlut -d ITS`) | /// | MFT | `MFT/Param/MatLUT` (`o2-gtrk-build-matlut -d MFT`) | /// | TRKFT3 | `TRK/Param/MatLUT` (`o2-gtrk-build-matlut -d TRKFT3`, one LUT for TRK and FT3) | +/// | TRKFT3TOF | `TRK/Param/MatLUTTOF` (`o2-gtrk-build-matlut -d TRKFT3 --trk-rmax-cm 95 --trk-zmax-cm 350`, to the TOF) | /// /// `MaterialCondition` is the condition input `Conditions` /// holds (Conditions.h): the devices that track fetch it, the measurement @@ -34,6 +35,7 @@ #include "GenericTracking/Detectors/ITS.h" #include "GenericTracking/Detectors/MFT.h" #include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" #include "GenericTracking/Workflow/DataSpecs.h" #include "DetectorsBase/GRPGeomHelper.h" @@ -62,11 +64,12 @@ template return std::same_as ? o2::header::DataOrigin{"GLO"} : detectorOrigin(); } -/// The CCDB path of \a Det's material LUT. +/// The CCDB path of \a Det's material LUT: TRKFT3TOF's its own, which +/// reaches the TOF, so that TRKFT3's stays TRKFT3's. template [[nodiscard]] std::string materialLutPath() { - return materialLutOrigin().template as() + "/Param/MatLUT"; + return materialLutOrigin().template as() + (std::same_as ? "/Param/MatLUTTOF" : "/Param/MatLUT"); } /// \a Det's material LUT as a condition input (see above). diff --git a/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/MeasurementProducer.h b/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/MeasurementProducer.h index 30c43b7c26677..2d2a8facc0b22 100644 --- a/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/MeasurementProducer.h +++ b/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/MeasurementProducer.h @@ -75,7 +75,9 @@ namespace o2::gtrk::workflow /// ordered by (layer, time block, phi cell, second cell, box start), plus the /// prefix offsets for those buckets. /// -/// Clusters arrive ordered by their readout frame. The counting sort is +/// Clusters arrive ordered by their readout frame -- on a layer timed per hit +/// (LayerSpec.h, `hitTimedLayers`) by their own box's start, which they keep +/// as their converter wrote it. The counting sort is /// stable, so the box starts inside every bucket remain ordered without /// another sort. The /// geometry transform runs once per cluster, from its sensor ID and local @@ -180,6 +182,7 @@ class MeasurementProducerTask : public o2::framework::Task const auto systematic2 = static_cast(param.clusterSystematicSigmaCM * param.clusterSystematicSigmaCM); const auto localVariance = [systematic2](float sigma) { return (sigma * sigma) + systematic2; }; const auto start = std::chrono::steady_clock::now(); + const std::int64_t durationPS = timeframeDurationPS(mConditions->orbitsPerTimeframe()); auto offsets = pc.outputs().make(o2::framework::Output{gDataOrigin, description(kMeasurements), kColGridOffsets}, static_cast(grid.bucketCount()) + 1U); MeasurementGridBuilder builder{std::span{offsets.data(), offsets.size()}}; @@ -206,12 +209,21 @@ class MeasurementProducerTask : public o2::framework::Task const auto variances = pointVariances(*mGeometry, cluster.chipID, static_cast(cluster.xLocal), point, varLoc0, 0.F, varLoc1); // Every frame's record where its layer's frames have theirs, every // lengthBC from BC 0: the boxes, the blocks and the slices' reach follow them. + // A layer timed per hit keeps the cluster's own box. const auto& frames = mFrames[point.layer]; - if (bcOfPS(cluster.timePS) % frames.lengthBC != 0 || bcOfPS(cluster.widthPS) != frames.lengthBC) { - LOGP(fatal, "a {} cluster's readout frame record [{}, {}) ps on layer {} is not one of the layer's frames of {} BC", Det::name, cluster.timePS, static_cast(cluster.timePS) + cluster.widthPS, point.layer, frames.lengthBC); - return; + if (Detector::isHitTimedLayer(point.layer)) { + if (cluster.widthPS == 0U || static_cast(cluster.timePS) + cluster.widthPS > durationPS) { + LOGP(fatal, "a {} cluster's time box [{}, {}) ps on layer {} is empty or outside the timeframe", Det::name, cluster.timePS, static_cast(cluster.timePS) + cluster.widthPS, point.layer); + return; + } + boxes[i] = {.start = cluster.timePS, .width = cluster.widthPS}; + } else { + if (bcOfPS(cluster.timePS) % frames.lengthBC != 0 || bcOfPS(cluster.widthPS) != frames.lengthBC) { + LOGP(fatal, "a {} cluster's readout frame record [{}, {}) ps on layer {} is not one of the layer's frames of {} BC", Det::name, cluster.timePS, static_cast(cluster.timePS) + cluster.widthPS, point.layer, frames.lengthBC); + return; + } + boxes[i] = measurementTimeBox(cluster, point.layer, param, frames); } - boxes[i] = measurementTimeBox(cluster, point.layer, param, frames); buckets[i] = grid.bucketAt(point.layer, boxes[i].start, point.phi, point.second); positions[i] = {point.x, point.y, point.z, point.r, point.phi, variances.z, variances.r, variances.rPhi}; bounds.add(static_cast(point.layer), grid.frames(point.layer), boxes[i], positions[i][5], positions[i][6], positions[i][7], varLoc0, varLoc1); diff --git a/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/RecoParam.h b/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/RecoParam.h index 84b5f1d6f6007..a1b2764fffd8e 100644 --- a/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/RecoParam.h +++ b/Detectors/GenericTracking/workflow/include/GenericTracking/Workflow/RecoParam.h @@ -15,10 +15,10 @@ /// A ConfigurableParam, where `--configKeyValues "GTRKReco.="` /// reaches them and every device of the chain sees the same value. /// -/// The fields are one struct, `RecoSettings`; each detector has its own -/// parameter of them, `RecoParam` (as `DPLAlpideParam`): -/// `GTRKRecoITS`, `GTRKRecoMFT`, `GTRKRecoTRK`, so that one workflow carries -/// every detector's. A detector layout's is `recoParam()`. +/// The layouts share the `RecoSettings` fields. Each layout reads its own +/// parameter through `recoParam()`: `GTRKRecoITS`, `GTRKRecoMFT`, +/// `GTRKRecoTRK` or `GTRKRecoTRKTOF`. Layer-indexed keys use the selected +/// layout's numbering. #ifndef GTRK_WORKFLOW_RECOPARAM_H_ #define GTRK_WORKFLOW_RECOPARAM_H_ @@ -34,11 +34,14 @@ // ENABLE_UPGRADES comes with DetID.h (UpgradesStatus.h). #ifdef ENABLE_UPGRADES #include "GenericTracking/Detectors/TRKFT3.h" +#include "GenericTracking/Detectors/TRKFT3TOF.h" #endif +#include #include #include #include +#include #include namespace o2::gtrk @@ -143,8 +146,8 @@ struct RecoSettings { /// tracks past a shorter layer's end are kept and those through a gap /// are not. std::vector iterationSkipLinks; - /// The layers each iteration's links join, a bit per layer; 0 for every - /// layer (the default). The vertexing pass's 7 takes layers 0-2 alone. + /// The layers each iteration's links join, a bit per layer; 0 takes the + /// layout's default seeding mask. The vertexing pass's 7 takes layers 0-2 alone. std::vector iterationLayerMask; /// The layers each iteration's roads may end on, a bit per layer; 0 for any /// (the default). O2's ITS async asks layer 3 or 6 of its third, @@ -156,11 +159,10 @@ struct RecoSettings { /// The lowest pT of a track by its cluster count [GeV], 0 for none -- the /// final track's: after the follow where the iteration follows, else the /// road's. Iteration - /// `i`'s floor for `n` clusters is entry `16 i + n`, so 16 entries per - /// iteration, or none for no floor at all. O2's ITS async asks 1/12 of 7 - /// clusters in every iteration, and 1/5, 1 and 1/6 of 6, 5 and 4 in its - /// third (entries 7, 23, 39, 38, 37, 36). - static constexpr int kClusterSlots = 16; + /// Each iteration has 18 entries indexed by cluster count (0 through 17). + /// The previous 16-entry format still applies to layouts with shorter chains. + static constexpr std::size_t kClusterSlots = 18U; + static constexpr std::size_t kLegacyClusterSlots = 16U; std::vector iterationClusterMinPtGeV; /// How many of a track's innermost clusters each iteration lets it share /// with another; 0, strict, by default. @@ -283,8 +285,7 @@ struct RecoParam : public o2::conf::ConfigurableParamPromoter, Reco template RecoParam RecoParam::sInstance; -/// A detector layout's O2 detector: its parameter's, its data origin's -/// (DataSpecs.h's `detectorOrigin`). +/// A detector layout's O2 detector and data origin (DataSpecs.h). template struct DetIDOf; template <> @@ -297,15 +298,29 @@ struct DetIDOf : std::integral_constant struct DetIDOf : std::integral_constant { }; +/// TRKFT3TOF publishes tracks with TRK's data origin. +template <> +struct DetIDOf : std::integral_constant { +}; #endif -/// A detector layout's parameter. +/// A detector layout's reconstruction parameters. template struct RecoParamOf { using type = RecoParam::value>; // NOLINT(readability-identifier-naming): a type trait's member }; -/// The settings of \a Det's parameter. +#ifdef ENABLE_UPGRADES +struct RecoParamTRKTOF : public o2::conf::ConfigurableParamPromoter { + O2ParamDef(RecoParamTRKTOF, "GTRKRecoTRKTOF"); +}; + +template <> +struct RecoParamOf { + using type = RecoParamTRKTOF; +}; +#endif + template [[nodiscard]] const RecoSettings& recoParam() { diff --git a/Detectors/GenericTracking/workflow/src/GTrkWorkflowLinkDef.h b/Detectors/GenericTracking/workflow/src/GTrkWorkflowLinkDef.h index eb37fffe8fbcd..ef7444d15209e 100644 --- a/Detectors/GenericTracking/workflow/src/GTrkWorkflowLinkDef.h +++ b/Detectors/GenericTracking/workflow/src/GTrkWorkflowLinkDef.h @@ -23,6 +23,8 @@ #ifdef ENABLE_UPGRADES #pragma link C++ class o2::gtrk::RecoParam < o2::detectors::DetID::TRK> + ; #pragma link C++ class o2::conf::ConfigurableParamPromoter < o2::gtrk::RecoParam < o2::detectors::DetID::TRK>, o2::gtrk::RecoSettings> + ; +#pragma link C++ class o2::gtrk::RecoParamTRKTOF + ; +#pragma link C++ class o2::conf::ConfigurableParamPromoter < o2::gtrk::RecoParamTRKTOF, o2::gtrk::RecoSettings> + ; #endif #pragma link C++ class o2::gtrk::workflow::ClusterShapeBand + ; diff --git a/Detectors/GenericTracking/workflow/src/RecoParam.cxx b/Detectors/GenericTracking/workflow/src/RecoParam.cxx index c4e9c426c0da5..b06879ffd0c36 100644 --- a/Detectors/GenericTracking/workflow/src/RecoParam.cxx +++ b/Detectors/GenericTracking/workflow/src/RecoParam.cxx @@ -19,5 +19,7 @@ static auto& sRecoParamITS = RecoParam::Instance(); static auto& sRecoParamMFT = RecoParam::Instance(); #ifdef ENABLE_UPGRADES static auto& sRecoParamTRK = RecoParam::Instance(); +O2ParamImpl(RecoParamTRKTOF); +static auto& sRecoParamTRKTOF = RecoParamTRKTOF::Instance(); #endif } // namespace o2::gtrk diff --git a/Detectors/Upgrades/ALICE3/IOTOF/DataFormatsIOTOF/include/DataFormatsIOTOF/Cluster.h b/Detectors/Upgrades/ALICE3/IOTOF/DataFormatsIOTOF/include/DataFormatsIOTOF/Cluster.h index b16a6e8bf2f39..6c36416bfc857 100644 --- a/Detectors/Upgrades/ALICE3/IOTOF/DataFormatsIOTOF/include/DataFormatsIOTOF/Cluster.h +++ b/Detectors/Upgrades/ALICE3/IOTOF/DataFormatsIOTOF/include/DataFormatsIOTOF/Cluster.h @@ -113,17 +113,19 @@ class Cluster static constexpr uint16_t InvalidPatternID = static_cast(ClusterInfo::MaskPattern); Cluster() = default; - Cluster(UShort_t row, UShort_t col, UShort_t rowSpan, UShort_t colSpan, UShort_t patt, UShort_t topo, UShort_t chipID = 0, time_t time = 0.0f) - : mChipID(chipID), mTime(time) + Cluster(UShort_t row, UShort_t col, UShort_t rowSpan, UShort_t colSpan, UShort_t patt, UShort_t topo, UShort_t chipID = 0, time_t time = 0.0f, uint64_t bc = 0, float timeWrtBc = 0.0f) + : mChipID(chipID), mTime(time), mBc(bc), mTimeWrtBc(timeWrtBc) { mClusterInfo.data = ClusterInfo::pack(row, col, rowSpan, colSpan, patt, topo); } - void set(UShort_t row, UShort_t col, UShort_t rowSpan, UShort_t colSpan, UShort_t patt, UShort_t topo, UShort_t chipID, time_t time) + void set(UShort_t row, UShort_t col, UShort_t rowSpan, UShort_t colSpan, UShort_t patt, UShort_t topo, UShort_t chipID, time_t time, uint64_t bc, float timeWrtBc) { mClusterInfo.data = ClusterInfo::pack(row, col, rowSpan, colSpan, patt, topo); mChipID = chipID; mTime = time; + mBc = bc; + mTimeWrtBc = timeWrtBc; } // Unpack Getters @@ -149,6 +151,9 @@ class Cluster uint32_t getChipID() const { return mChipID; } uint32_t getSensorID() const { return mChipID; } time_t getTime() const { return mTime; } + uint64_t getBc() const { return mBc; } + float getTimeWrtBc() const { return mTimeWrtBc; } + uint64_t getPackedData() const { return mClusterInfo.data; } // Setters @@ -160,6 +165,8 @@ class Cluster void setTopology(UShort_t t) { mClusterInfo.setTopology(t); } void setChipID(UShort_t c) { mChipID = c; } void setTime(time_t t) { mTime = t; } + void setBc(uint64_t bc) { mBc = bc; } + void setTimeWrtBc(float timeWrtBc) { mTimeWrtBc = timeWrtBc; } // Operators & Debugging bool operator==(const Cluster& cl) const @@ -174,6 +181,8 @@ class Cluster ClusterInfo mClusterInfo{}; ///< 64-bit packed structure containing geometry/topology UShort_t mChipID{0}; ///< Chip / Sensor ID float mTime{0.0f}; ///< Hit timing information + uint64_t mBc{0}; ///< Number of bunch crossing + float mTimeWrtBc{0.0f}; ///< Cluster time w.r.t. BC void sanityCheck(); diff --git a/Detectors/Upgrades/ALICE3/IOTOF/reconstruction/include/IOTOFReconstruction/Clusterer.h b/Detectors/Upgrades/ALICE3/IOTOF/reconstruction/include/IOTOFReconstruction/Clusterer.h index 9409339a02623..aae4ebac94e97 100644 --- a/Detectors/Upgrades/ALICE3/IOTOF/reconstruction/include/IOTOFReconstruction/Clusterer.h +++ b/Detectors/Upgrades/ALICE3/IOTOF/reconstruction/include/IOTOFReconstruction/Clusterer.h @@ -24,6 +24,7 @@ #include "SimulationDataFormat/ConstMCTruthContainer.h" #include "SimulationDataFormat/MCCompLabel.h" #include "SimulationDataFormat/MCTruthContainer.h" +#include "CommonConstants/LHCConstants.h" #include #include #include diff --git a/Detectors/Upgrades/ALICE3/IOTOF/reconstruction/src/Clusterer.cxx b/Detectors/Upgrades/ALICE3/IOTOF/reconstruction/src/Clusterer.cxx index 06e240bbbec27..af5837ccc8c0a 100644 --- a/Detectors/Upgrades/ALICE3/IOTOF/reconstruction/src/Clusterer.cxx +++ b/Detectors/Upgrades/ALICE3/IOTOF/reconstruction/src/Clusterer.cxx @@ -170,11 +170,15 @@ void Clusterer::ClustererThread::findClustersSingleHit(gsl::span di const ConstDigitTruth* labelsDigPtr, ClusterTruth* labelsClusPtr) { + const auto& digitizerParams = o2::iotof::DPLDigitizerParam::Instance(); const auto& digit = digits[digitIdx]; const uint16_t chipID = digit.getChipIndex(); const uint16_t row = digit.getRow(); const uint16_t col = digit.getColumn(); - const time_t time = digit.getTime(); + // const time_t time = digit.getTime(); + const uint64_t nbc = digit.getBc(); + const float timeWrtBc = digit.getTdc() * digitizerParams.tdcBin; + const time_t time = timeWrtBc + nbc * o2::constants::lhc::LHCBunchSpacingNS; if (labelsClusPtr) { int nStoredLabels = 0; @@ -192,7 +196,7 @@ void Clusterer::ClustererThread::findClustersSingleHit(gsl::span di constexpr uint16_t firedDigitsMask = (1U << 0); // 0x0001 (1) mClsTopoClassifier.getTopology(firedDigitsMask, minRow, rowSpan, minCol, colSpan, clsTopology); // Bit 0 corresponds to (rowOffset=0, colOffset=0) in row-major order - Cluster cluster(row, col, rowSpan, colSpan, firedDigitsMask, clsTopology, chipID, time); + Cluster cluster(row, col, rowSpan, colSpan, firedDigitsMask, clsTopology, chipID, time, nbc, timeWrtBc); LOG(debug) << "Pushing back cluster with row: " << row << ", col: " << col << ", rowSpan: " << static_cast(rowSpan) << ", colSpan: " << static_cast(colSpan) @@ -270,7 +274,10 @@ void Clusterer::ClustererThread::findClustersMultipleHits(gsl::span const auto& digit = digits[precluster[0]]; const uint16_t row = digit.getRow(); const uint16_t col = digit.getColumn(); - const time_t time = digit.getTime(); + // const time_t time = digit.getTime(); + const uint64_t nbc = digit.getBc(); + const float timeWrtBc = digit.getTdc() * digitizerParams.tdcBin; + const time_t time = timeWrtBc + nbc * o2::constants::lhc::LHCBunchSpacingNS; if (labelsClusPtr) { int nMcLabels = 0; @@ -288,7 +295,7 @@ void Clusterer::ClustererThread::findClustersMultipleHits(gsl::span constexpr uint16_t firedDigitsMask = (1U << 0); // 0x0001 (1) mClsTopoClassifier.getTopology(firedDigitsMask, minRow, rowSpan, minCol, colSpan, clsTopology); // Bit 0 corresponds to (rowOffset=0, colOffset=0) in row-major order - Cluster cluster(minRow, minCol, rowSpan, colSpan, firedDigitsMask, clsTopology, chipID, time); + Cluster cluster(minRow, minCol, rowSpan, colSpan, firedDigitsMask, clsTopology, chipID, time, nbc, timeWrtBc); LOG(debug) << "Pushing back cluster with row: " << row << ", col: " << col << ", rowSpan: " << static_cast(rowSpan) << ", colSpan: " << static_cast(colSpan) @@ -314,19 +321,23 @@ void Clusterer::ClustererThread::findClustersMultipleHits(gsl::span minCol = std::min(minCol, digit.getColumn()); maxRow = std::max(maxRow, digit.getRow()); maxCol = std::max(maxCol, digit.getColumn()); - clsTime += digit.getTime(); + const time_t time = digit.getTdc() * digitizerParams.tdcBin + digit.getBc() * o2::constants::lhc::LHCBunchSpacingNS; + clsTime += time; fetchMCLabels(idx, labelsDigPtr, nMcLabels); } clsTime /= precluster.size(); const uint8_t rowSpan = maxRow - minRow + 1; const uint8_t colSpan = maxCol - minCol + 1; + const uint64_t nbc = static_cast(clsTime / o2::constants::lhc::LHCBunchSpacingNS); + const float timeWrtBc = clsTime - nbc * o2::constants::lhc::LHCBunchSpacingNS; + // Fired digits bitmask packed into a single 16-bit pattern variable uint16_t firedDigitsMask = 0; if (rowSpan * colSpan > maxFiredDigitsForCls) { // Overflow precluster: pass InvalidPatternID (or 0) and kHuge topology flag - Cluster cluster(minRow, minCol, rowSpan, colSpan, Cluster::InvalidPatternID, Topologies::kHuge, chipID, clsTime); + Cluster cluster(minRow, minCol, rowSpan, colSpan, Cluster::InvalidPatternID, Topologies::kHuge, chipID, clsTime, nbc, timeWrtBc); mClusters.emplace_back(cluster); mPatterns.emplace_back(Cluster::InvalidPatternID); continue; @@ -354,7 +365,7 @@ void Clusterer::ClustererThread::findClustersMultipleHits(gsl::span for (int i = 0; i < nMcLabels; i++) { mLabels.addElement(nStoredCls, mLabelsBuff[i]); } - Cluster cluster(minRow, minCol, rowSpan, colSpan, firedDigitsMask, clsTopology, chipID, clsTime); + Cluster cluster(minRow, minCol, rowSpan, colSpan, firedDigitsMask, clsTopology, chipID, clsTime, nbc, timeWrtBc); LOG(debug) << "Pushing back cluster with row: " << minRow << ", col: " << minCol << ", rowSpan: " << static_cast(rowSpan) << ", colSpan: " << static_cast(colSpan) << ", pattern: " << firedDigitsMask << ", topology: " << static_cast(clsTopology) diff --git a/Detectors/Upgrades/ALICE3/IOTOF/workflow/CMakeLists.txt b/Detectors/Upgrades/ALICE3/IOTOF/workflow/CMakeLists.txt index 14a0e215587d8..5a1982824ae26 100644 --- a/Detectors/Upgrades/ALICE3/IOTOF/workflow/CMakeLists.txt +++ b/Detectors/Upgrades/ALICE3/IOTOF/workflow/CMakeLists.txt @@ -15,12 +15,14 @@ o2_add_library(IOTOFWorkflow src/DigitWriterSpec.cxx src/ClustererSpec.cxx src/ClusterWriterSpec.cxx + src/ClusterReaderSpec.cxx src/RecoWorkflow.cxx PUBLIC_LINK_LIBRARIES O2::Framework O2::DataFormatsIOTOF O2::DataFormatsITSMFT O2::IOTOFReconstruction O2::DPLUtils + O2::SimulationDataFormat ) o2_add_executable(reco-workflow diff --git a/Detectors/Upgrades/ALICE3/IOTOF/workflow/include/IOTOFWorkflow/ClusterReaderSpec.h b/Detectors/Upgrades/ALICE3/IOTOF/workflow/include/IOTOFWorkflow/ClusterReaderSpec.h new file mode 100644 index 0000000000000..ce11c37f4f1d9 --- /dev/null +++ b/Detectors/Upgrades/ALICE3/IOTOF/workflow/include/IOTOFWorkflow/ClusterReaderSpec.h @@ -0,0 +1,65 @@ +// Copyright 2019-2020 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 ClusterReaderSpec.h +/// \brief The TF3 clusters of o2-alice3-iotof-reco-workflow's cluster file +/// (ClusterWriterSpec.h), one timeframe per entry. + +#ifndef O2_IOTOF_CLUSTERREADERSPEC_H +#define O2_IOTOF_CLUSTERREADERSPEC_H + +#include "DataFormatsIOTOF/Cluster.h" +#include "DataFormatsITSMFT/ROFRecord.h" +#include "Framework/DataProcessorSpec.h" +#include "Framework/Task.h" +#include "SimulationDataFormat/MCCompLabel.h" +#include "SimulationDataFormat/MCTruthContainer.h" + +#include +#include + +#include +#include +#include + +namespace o2::iotof +{ + +/// Publishes TF3/CLUSTERS, TF3/PATTERNS, TF3/CLUSTERSROF and, with MC, +/// TF3/CLUSTERSMCTR (subspec 0) from the tree `o2sim` of `--tf3-cluster-infile`, +/// as the clusterer publishes them; an empty timeframe past the tree's last +/// entry. +class ClusterReader : public o2::framework::Task +{ + public: + explicit ClusterReader(bool useMC) : mUseMC(useMC) {} + void init(o2::framework::InitContext& ic) final; + void run(o2::framework::ProcessingContext& pc) final; + + private: + void connectTree(const std::string& filename); + + std::unique_ptr mFile; + std::unique_ptr mTree; + std::vector* mClusters = nullptr; + std::vector* mPatterns = nullptr; + std::vector* mROFs = nullptr; + o2::dataformats::MCTruthContainer* mLabels = nullptr; + bool mUseMC = false; +}; + +/// The reader's device, `tf3-cluster-reader`; its file `--tf3-cluster-infile` +/// (tf3clusters.root by default). +o2::framework::DataProcessorSpec getIOTOFClusterReaderSpec(bool useMC); + +} // namespace o2::iotof + +#endif // O2_IOTOF_CLUSTERREADERSPEC_H diff --git a/Detectors/Upgrades/ALICE3/IOTOF/workflow/src/ClusterReaderSpec.cxx b/Detectors/Upgrades/ALICE3/IOTOF/workflow/src/ClusterReaderSpec.cxx new file mode 100644 index 0000000000000..49e0d7ea3ccf0 --- /dev/null +++ b/Detectors/Upgrades/ALICE3/IOTOF/workflow/src/ClusterReaderSpec.cxx @@ -0,0 +1,109 @@ +// Copyright 2019-2020 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 ClusterReaderSpec.cxx +/// \brief The TF3 cluster reader (ClusterReaderSpec.h). + +#include "IOTOFWorkflow/ClusterReaderSpec.h" + +#include "Framework/ConfigParamRegistry.h" +#include "Framework/ControlService.h" +#include "Framework/Logger.h" +#include "Headers/DataHeader.h" + +#include +#include + +using namespace o2::framework; + +namespace o2::iotof +{ + +void ClusterReader::init(InitContext& ic) +{ + connectTree(ic.options().get("tf3-cluster-infile")); +} + +void ClusterReader::run(ProcessingContext& pc) +{ + const auto entry = mTree->GetReadEntry() + 1; + // A timeframe without a collision has no entry: publish empty streams, so + // that the consumers still see the timeframe (as TRK's reader does). + const bool noEntry = entry >= mTree->GetEntries(); + if (noEntry) { + LOG(info) << "TF3ClusterReader: no entry to read, publishing empty output"; + } else { + mTree->GetEntry(entry); + } + static const std::vector noClusters; + static const std::vector noPatterns; + static const std::vector noROFs; + static const o2::dataformats::MCTruthContainer noLabels; + const auto& clusters = noEntry ? noClusters : *mClusters; + LOG(info) << "TF3ClusterReader pushes " << clusters.size() << " clusters at entry " << entry; + pc.outputs().snapshot(Output{o2::header::gDataOriginTF3, "CLUSTERS", 0}, clusters); + pc.outputs().snapshot(Output{o2::header::gDataOriginTF3, "PATTERNS", 0}, noEntry ? noPatterns : *mPatterns); + pc.outputs().snapshot(Output{o2::header::gDataOriginTF3, "CLUSTERSROF", 0}, noEntry ? noROFs : *mROFs); + if (mUseMC) { + pc.outputs().snapshot(Output{o2::header::gDataOriginTF3, "CLUSTERSMCTR", 0}, noEntry ? noLabels : *mLabels); + } + if (noEntry || mTree->GetReadEntry() + 1 >= mTree->GetEntries()) { + pc.services().get().endOfStream(); + pc.services().get().readyToQuit(QuitRequest::Me); + } +} + +void ClusterReader::connectTree(const std::string& filename) +{ + mTree.reset(); + mFile.reset(TFile::Open(filename.c_str())); + if (!mFile || mFile->IsZombie()) { + throw std::runtime_error("TF3ClusterReader: cannot open " + filename); + } + mTree.reset(mFile->Get("o2sim")); + if (!mTree) { + throw std::runtime_error("TF3ClusterReader: no tree o2sim in " + filename); + } + const auto connect = [this](const char* name, auto*& address) { + if (!mTree->GetBranch(name)) { + throw std::runtime_error(std::format("TF3ClusterReader: no branch {}", name)); + } + if (const Int_t status = mTree->SetBranchAddress(name, &address); status < 0) { + throw std::runtime_error(std::format("TF3ClusterReader: cannot set the address of {} ({})", name, status)); + } + }; + connect("TF3Cluster", mClusters); + connect("TF3ClusterPatt", mPatterns); + connect("TF3ClusterROF", mROFs); + if (mUseMC) { + connect("TF3ClusterMCTruth", mLabels); + } + LOG(info) << "TF3ClusterReader: " << filename << " with " << mTree->GetEntries() << " entries"; +} + +DataProcessorSpec getIOTOFClusterReaderSpec(bool useMC) +{ + std::vector outputs{{o2::header::gDataOriginTF3, "CLUSTERS", 0, Lifetime::Timeframe}, + {o2::header::gDataOriginTF3, "PATTERNS", 0, Lifetime::Timeframe}, + {o2::header::gDataOriginTF3, "CLUSTERSROF", 0, Lifetime::Timeframe}}; + if (useMC) { + outputs.emplace_back(o2::header::gDataOriginTF3, "CLUSTERSMCTR", 0, Lifetime::Timeframe); + } + return DataProcessorSpec{ + .name = "tf3-cluster-reader", + .inputs = Inputs{}, + .outputs = outputs, + .algorithm = AlgorithmSpec{adaptFromTask(useMC)}, + .options = Options{{"tf3-cluster-infile", VariantType::String, "tf3clusters.root", {"Name of the input cluster file"}}}, + }; +} + +} // namespace o2::iotof