Project
Loading...
Searching...
No Matches
DCStoDPLconverter.h
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
12#ifndef O2_DCS_TO_DPL_CONVERTER
13#define O2_DCS_TO_DPL_CONVERTER
14
18#include <fairmq/Parts.h>
19#include <fairmq/Device.h>
24#include <unordered_map>
25#include <functional>
26#include <string_view>
27#include <chrono>
28
29namespace o2h = o2::header;
30namespace o2f = o2::framework;
31
32// we need to provide hash function for the DataDescription
33namespace std
34{
35template <>
37 std::size_t operator()(const o2h::DataDescription& d) const noexcept
38 {
39 return std::hash<std::string_view>{}({d.str, size_t(d.size)});
40 }
41};
42} // namespace std
43
44namespace o2::dcs
45{
49
52
53o2f::InjectorFunction dcs2dpl(std::unordered_map<DPID, std::vector<o2h::DataDescription>>& dpid2group, bool fbiFirst, bool verbose = false, int FBIPerInterval = 1)
54{
55
56 return [dpid2group, fbiFirst, verbose, FBIPerInterval](o2::framework::TimingInfo& tinfo, framework::ServiceRegistryRef const& services, fair::mq::Parts& parts, o2f::ChannelRetriever channelRetriever, size_t newTimesliceId, bool& stop) -> bool {
57 auto *device = services.get<framework::RawDeviceService>().device();
58 static std::unordered_map<DPID, DPCOM> cache; // will keep only the latest measurement in the 1-second wide window for each DPID
59 static std::unordered_map<std::string, int> sentToChannel;
60 static auto timer = std::chrono::high_resolution_clock::now();
61 static auto timer0 = std::chrono::high_resolution_clock::now();
62 static bool seenFBI = false;
63 static uint32_t localTFCounter = 0;
64 static size_t nInp = 0, nInpFBI = 0;
65 static size_t szInp = 0, szInpFBI = 0;
66 if (verbose) {
67 LOG(info) << "In lambda function: ********* Size of unordered_map (--> number of defined groups) = " << dpid2group.size();
68 }
69 // check if we got FBI (Master) or delta (MasterDelta)
70 if (!parts.Size()) {
71 LOGP(warn, "Empty input recieved at timeslice {}", tinfo.timeslice);
72 return false;
73 }
74 std::string firstName = std::string((char*)&(reinterpret_cast<const DPCOM*>(parts.At(0)->GetData()))->id);
75
76 bool isFBI = false;
77 nInp++;
78 if (o2::utils::Str::endsWith(firstName, "Master")) {
79 isFBI = true;
80 nInpFBI++;
81 seenFBI = true;
82 } else if (o2::utils::Str::endsWith(firstName, "MasterDelta")) {
83 isFBI = false;
84 } else {
85 LOGP(error, "Cannot determine if the map is FBI or Delta, 1st DP name is {}", firstName);
86 }
87 if (verbose) {
88 LOGP(info, "New input of {} parts received, map type: {}, timeslice {}", parts.Size(), isFBI ? "FBI" : "Delta", tinfo.timeslice);
89 }
90
91 // We first iterate over the parts of the received message
92 for (size_t i = 0; i < parts.Size(); ++i) { // DCS sends only 1 part, but we should be able to receive more
93 auto sz = parts.At(i)->GetSize();
94 szInp += sz;
95 if (isFBI) {
96 szInpFBI += sz;
97 }
98 auto nDPCOM = sz / sizeof(DPCOM); // number of DPCOM in current part
99 LOGP(debug, "sz={} szof={} -> /={} %={} | {} {}", sz, sizeof(DPCOM), nDPCOM, sz % sizeof(DPCOM), sizeof(o2::dcs::DataPointIdentifier), sizeof(o2::dcs::DataPointValue));
100 for (size_t j = 0; j < nDPCOM; j++) {
101 const auto* ptr = (reinterpret_cast<const DPCOM*>(parts.At(i)->GetData()) + j);
102 DPCOM src;
103 memcpy(&src, ptr, sizeof(DPCOM));
104 // do we want to check if this DP was requested ?
105 auto mapEl = dpid2group.find(src.id);
106 if (verbose) {
107 std::string dest;
108 if (mapEl == dpid2group.end()) {
109 dest = "none";
110 } else {
111 for (const auto& ds : mapEl->second) {
112 dest += fmt::format("{}, ", ds.as<std::string>());
113 }
114 }
115 LOG(info) << "Received DP " << src.id << " (data = " << src.data << "), matched to output-> " << dest;
116 }
117 if (mapEl != dpid2group.end()) {
118 cache[src.id] = src; // this is needed in case in the 1s window we get a new value for the same DP
119 }
120 }
121 }
122 auto timerNow = std::chrono::high_resolution_clock::now();
123 if (fbiFirst && nInpFBI < 2) { // 1st FBI might be obsolete
124 seenFBI = false;
125 static int prevDelay = 0;
126 std::chrono::duration<double, std::ratio<1>> duration = timerNow - timer0;
127 int delay = duration.count();
128 if (delay > prevDelay) {
129 LOGP(info, "Waiting for requested 1st FBI since {} s", delay);
130 prevDelay = delay;
131 }
132 }
133
134 std::chrono::duration<double, std::ratio<1>> duration = timerNow - timer;
135 bool didSendMessages = false;
136 if (duration.count() > 1 && (seenFBI || !fbiFirst)) { // did we accumulate for 1 sec and have we seen FBI if it was requested?
137 std::unordered_map<o2h::DataDescription, pmr::vector<DPCOM>, std::hash<o2h::DataDescription>> outputs;
138 // in the cache we have the final values of the DPs that we should put in the output
139 // distribute DPs over the vectors for each requested output
140 for (auto& it : cache) {
141 auto mapEl = dpid2group.find(it.first);
142 if (mapEl != dpid2group.end()) {
143 for (const auto& ds : mapEl->second) {
144 outputs[ds].push_back(it.second);
145 }
146 }
147 }
148 std::uint64_t creation = std::chrono::time_point_cast<std::chrono::milliseconds>(timerNow).time_since_epoch().count();
149 std::unordered_map<std::string, std::unique_ptr<fair::mq::Parts>> messagesPerRoute;
150 // create and send output messages
151 for (auto& it : outputs) { // distribute messages per routes
152 o2h::DataHeader hdr(it.first, "DCS", 0);
153 o2f::OutputSpec outsp{hdr.dataOrigin, hdr.dataDescription, hdr.subSpecification};
154 if (it.second.empty()) {
155 LOG(warning) << "No data for OutputSpec " << outsp;
156 continue;
157 }
158 auto channel = channelRetriever(outsp, tinfo.timeslice);
159 if (channel.empty()) {
160 LOG(warning) << "No output channel found for OutputSpec " << outsp << ", discarding its data";
161 it.second.clear();
162 continue;
163 }
164
165 hdr.tfCounter = localTFCounter; // this also
166 hdr.payloadSerializationMethod = o2h::gSerializationMethodNone;
167 hdr.splitPayloadParts = 1;
168 hdr.splitPayloadIndex = 1;
169 hdr.payloadSize = it.second.size() * sizeof(DPCOM);
170 hdr.firstTForbit = 0; // this should be irrelevant for DCS
171 o2h::Stack headerStack{hdr, o2::framework::DataProcessingHeader{tinfo.timeslice, 1, creation}};
172 auto fmqFactory = device->GetChannel(channel).Transport();
173 auto hdMessage = fmqFactory->CreateMessage(headerStack.size(), fair::mq::Alignment{64});
174 auto plMessage = fmqFactory->CreateMessage(hdr.payloadSize, fair::mq::Alignment{64});
175 memcpy(hdMessage->GetData(), headerStack.data(), headerStack.size());
176 memcpy(plMessage->GetData(), it.second.data(), hdr.payloadSize);
177
178 fair::mq::Parts* parts2send = messagesPerRoute[channel].get(); // fair::mq::Parts*
179 if (!parts2send) {
180 messagesPerRoute[channel] = std::make_unique<fair::mq::Parts>();
181 parts2send = messagesPerRoute[channel].get();
182 }
183 parts2send->AddPart(std::move(hdMessage));
184 parts2send->AddPart(std::move(plMessage));
185 if (verbose) {
186 LOGP(info, "Pushing {} DPs to {} for TimeSlice {} at {}", it.second.size(), o2f::DataSpecUtils::describe(outsp), tinfo.timeslice, creation);
187 }
188 it.second.clear();
189 }
190 // push output of every route
191 for (auto& msgIt : messagesPerRoute) {
192 if (verbose) {
193 LOG(info) << "Sending " << msgIt.second->Size() / 2 << " parts to channel " << msgIt.first;
194 }
195 o2f::sendOnChannel(*device, *msgIt.second.get(), msgIt.first, tinfo.timeslice);
196 sentToChannel[msgIt.first]++;
197 didSendMessages |= msgIt.second->Size() > 0;
198 }
199 timer = timerNow;
200 cache.clear();
201 if (!messagesPerRoute.empty()) {
202 localTFCounter++;
203 }
204 }
205 if (isFBI && ((nInpFBI % FBIPerInterval) == 0 || verbose)) {
206 float runtime = 1e-3 * std::chrono::duration_cast<std::chrono::milliseconds>(timerNow - timer0).count();
207 std::string sent = "Sent since last FBI report: ";
208 for (auto& m : sentToChannel) {
209 auto pos = m.first.find("_to_");
210 sent += fmt::format("{}:{} ", m.first.substr(pos != std::string::npos ? pos + 4 : 0), m.second);
211 m.second = 0;
212 }
213 LOGP(info, "{} inputs ({} bytes) of which {} FBI ({} bytes) seen in {:.3f} s | {}", nInp, fmt::group_digits(szInp), nInpFBI, fmt::group_digits(szInpFBI), runtime, sent);
214 }
215 return didSendMessages;
216 };
217}
218
219} // namespace o2
220
221#endif /* O2_DCS_TO_DPL_CONVERTER_H */
uint32_t hash
std::ostringstream debug
unsigned int uint32_t
int32_t i
TPCZSHDR * hdr
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char e
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char Directory with events to Events directory is and not inside events d
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder Print launch bounds used for RTC code as debugging for exit after Allow RTC with slave GPUReconstruction instances with optConstexpr and optSpecialcode Maximum number of RTC cache files per backend in the cache the oldest are Prepend RTC compilation commands by this string Load a parameter object containing the launch bounds from a file h configStandalone Processing proc_param TPC Cluster Z Error Parameterization h configStandalone Processing settings for neural network proc_nn std::string Specify inference device(cpu(default), rocm, cuda)") AddOption(nnInferenceDeviceId
char error[CURL_ERROR_SIZE]
uint16_t pos
Definition RawData.h:3
uint32_t j
Definition RawData.h:0
TBranch * ptr
InjectorFunction dcs2dpl()
const GLfloat * m
Definition glcorearb.h:4066
GLenum src
Definition glcorearb.h:1767
o2::dcs::DataPointCompositeObject DPCOM
Defining ITS Vertex explicitly as messageable.
Definition Cartesian.h:288
std::function< bool(TimingInfo &, ServiceRegistryRef const &services, fair::mq::Parts &inputs, ChannelRetriever, size_t newTimesliceId, bool &stop)> InjectorFunction
void sendOnChannel(fair::mq::Device &device, o2::header::Stack &&headerStack, fair::mq::MessagePtr &&payloadMessage, OutputSpec const &spec, ChannelRetriever &channelRetriever)
std::function< std::string const &(OutputSpec const &, DataProcessingHeader::StartTime)> ChannelRetriever
O2 data header classes and API, v0.1.
Definition DetID.h:51
constexpr o2::header::SerializationMethod gSerializationMethodNone
Definition DataHeader.h:330
the main header struct
Definition DataHeader.h:623
static int constexpr size
Definition DataHeader.h:210
a move-only header stack with serialized headers This is the flat buffer where all the headers in a m...
Definition Stack.h:33
static bool endsWith(const std::string &s, const std::string &ending)
std::size_t operator()(const o2h::DataDescription &d) const noexcept
o2::mch::DsIndex ds
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"