-
Notifications
You must be signed in to change notification settings - Fork 513
Expand file tree
/
Copy pathExternalDetector.cxx
More file actions
451 lines (406 loc) · 15.6 KB
/
Copy pathExternalDetector.cxx
File metadata and controls
451 lines (406 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// 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.
#include "ExternalDetectors/ExternalDetector.h"
#include "CADSupport/CADGeometryUtils.h"
#include "DetectorsBase/Stack.h"
#include "CommonUtils/ConfigurationMacroHelper.h"
#include "CommonUtils/FileSystemUtils.h"
#include "CommonUtils/ShmManager.h"
#include "CommonUtils/ShmAllocator.h"
#include <FairRootManager.h>
#include <FairVolume.h>
#include <fairlogger/Logger.h>
#include <TGeoManager.h>
#include <TGeoMatrix.h>
#include <TGeoMedium.h>
#include <TGeoNode.h>
#include <TGeoVolume.h>
#include <TVirtualMC.h>
#include <TVector3.h>
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
#include <rapidjson/istreamwrapper.h>
#include <fstream>
namespace o2::ext
{
ExternalDetector::ExternalDetector(const char* name, const char* title, ExternalDetectorOptions options)
: o2::base::DetImpl<ExternalDetector>(name, true),
mOptions(options),
mTrackData(),
mHits(o2::utils::createSimVector<o2::ext::Hit>())
{
(void)title; // the FairModule title is the second base ctor argument; kept for symmetry with other detectors
// Decouple the user-facing FairModule name (e.g. "IRIS") from the DetId: the base
// ctor derives fDetId from the name which is generally not a registered DetID, so we
// explicitly tie this detector to the configured (existing) DetID. This is what makes
// the hit output format / identity well defined, as discussed.
fDetId = mOptions.detID;
}
ExternalDetector::ExternalDetector()
: o2::base::DetImpl<ExternalDetector>("EXTDET", true),
mTrackData(),
mHits(o2::utils::createSimVector<o2::ext::Hit>())
{
}
ExternalDetector::ExternalDetector(const ExternalDetector& rhs)
: o2::base::DetImpl<ExternalDetector>(rhs),
mOptions(rhs.mOptions),
mSensitiveVolumeNames(rhs.mSensitiveVolumeNames),
mSensitiveVolIDs(rhs.mSensitiveVolIDs),
mVolID2SensorID(rhs.mVolID2SensorID),
mTrackData(),
mHits(o2::utils::createSimVector<o2::ext::Hit>())
{
}
ExternalDetector::~ExternalDetector()
{
if (mHits) {
o2::utils::freeSimVector(mHits);
}
}
void ExternalDetector::collectSensitiveVolumeNames(TGeoVolume* vol, std::set<TGeoVolume*>& visited)
{
if (!vol || visited.count(vol)) {
return;
}
visited.insert(vol);
bool sensitive = false;
// match by volume name
const std::string volname = vol->GetName();
for (const auto& token : mOptions.sensitiveVolumes) {
if (!token.empty() && volname.find(token) != std::string::npos) {
sensitive = true;
break;
}
}
// otherwise match by medium name
if (!sensitive) {
if (auto medium = vol->GetMedium()) {
const std::string medname = medium->GetName();
for (const auto& token : mOptions.sensitiveMedia) {
if (!token.empty() && medname.find(token) != std::string::npos) {
sensitive = true;
break;
}
}
}
}
if (sensitive) {
mSensitiveVolumeNames.emplace_back(volname);
}
const int nd = vol->GetNdaughters();
for (int i = 0; i < nd; ++i) {
if (auto node = vol->GetNode(i)) {
collectSensitiveVolumeNames(node->GetVolume(), visited);
}
}
}
void ExternalDetector::ConstructGeometry()
{
// build the CAD geometry and obtain its top volume
auto module_top = o2::cad::buildCADVolumeFromMacro(mOptions.root_macro_file, GetName());
if (!module_top) {
LOG(error) << "No geometry could be built for external detector " << GetName();
return;
}
// bring the CAD media under O2's MaterialManager
o2::cad::remapCADMedia(module_top, GetName());
// determine which volumes should become sensitive (selected by medium name)
mSensitiveVolumeNames.clear();
std::set<TGeoVolume*> visited;
collectSensitiveVolumeNames(module_top, visited);
if (mSensitiveVolumeNames.empty()) {
LOG(warning) << "External detector " << GetName() << ": no volume matched the configured sensitive media; "
<< "no hits will be produced";
} else {
LOG(info) << "External detector " << GetName() << ": " << mSensitiveVolumeNames.size()
<< " sensitive volume(s) selected";
}
// place it into the provided anchor volume (needs to exist)
auto anchor = gGeoManager->FindVolumeFast(mOptions.anchor_volume.c_str());
if (!anchor) {
LOG(error) << "Anchor volume " << mOptions.anchor_volume << " not found. Aborting";
return;
}
anchor->AddNode(module_top, 1, const_cast<TGeoMatrix*>(mOptions.placement));
}
void ExternalDetector::InitializeO2Detector()
{
// resolve the MC volume IDs of the sensitive volumes and register them with FairRoot
mSensitiveVolIDs.clear();
mVolID2SensorID.clear();
int sensorID = 0;
for (const auto& name : mSensitiveVolumeNames) {
const int volID = registerSensitiveVolumeAndGetVolID(name);
if (volID <= 0) {
continue;
}
mSensitiveVolIDs.insert(volID);
mVolID2SensorID[volID] = sensorID++;
LOG(info) << "External detector " << GetName() << ": registered sensitive volume '" << name
<< "' (MC volID " << volID << ", sensor " << mVolID2SensorID[volID] << ")";
}
// optionally load a user-provided sensitive action from a ROOT macro (same mechanism as
// generator/stepping hooks). When given, it fully replaces the built-in action.
if (!mOptions.sensitiveMacro.empty()) {
const auto file = o2::utils::expandShellVarsInFileName(mOptions.sensitiveMacro);
const auto func = mOptions.sensitiveFunction.empty() ? std::string("sensitiveAction()") : mOptions.sensitiveFunction;
const auto unique = std::string("o2ext_sensitive_action_") + GetName();
mSensitiveAction = o2::conf::GetFromMacro<SensitiveFcn>(file, func, "o2::ext::ExternalDetector::SensitiveFcn", unique);
if (mSensitiveAction) {
LOG(info) << "External detector " << GetName() << ": using sensitive action '" << func
<< "' from macro '" << file << "'";
} else {
LOG(fatal) << "External detector " << GetName() << ": could not load sensitive action '" << func
<< "' from macro '" << file << "'";
}
}
}
Bool_t ExternalDetector::ProcessHits(FairVolume* vol)
{
// This method is called from the MC stepping for the registered sensitive volumes.
// Remember the current volume so the action helpers (currentSensorID()) can resolve it,
// then either run the user-provided action or the built-in one.
mCurrentVolume = vol;
++mStepCount; // probe: count stepping calls inside our sensitive volumes
if (mSensitiveAction) {
return mSensitiveAction(this) ? kTRUE : kFALSE;
}
return defaultProcessHits();
}
Bool_t ExternalDetector::defaultProcessHits()
{
if (!(fMC->TrackCharge())) {
return kFALSE;
}
const int sensorID = currentSensorID();
if (sensorID < 0) {
return kFALSE; // not one of our sensitive volumes
}
bool startHit = false, stopHit = false;
unsigned char status = 0;
if (fMC->IsTrackEntering()) {
status |= o2::ext::Hit::kTrackEntering;
}
if (fMC->IsTrackInside()) {
status |= o2::ext::Hit::kTrackInside;
}
if (fMC->IsTrackExiting()) {
status |= o2::ext::Hit::kTrackExiting;
}
if (fMC->IsTrackOut()) {
status |= o2::ext::Hit::kTrackOut;
}
if (fMC->IsTrackStop()) {
status |= o2::ext::Hit::kTrackStopped;
}
if (fMC->IsTrackAlive()) {
status |= o2::ext::Hit::kTrackAlive;
}
// track is entering or created in the volume
if ((status & o2::ext::Hit::kTrackEntering) || (status & o2::ext::Hit::kTrackInside && !mTrackData.mHitStarted)) {
startHit = true;
} else if ((status & (o2::ext::Hit::kTrackExiting | o2::ext::Hit::kTrackOut | o2::ext::Hit::kTrackStopped))) {
stopHit = true;
}
// increment energy loss at all steps except entrance
if (!startHit) {
mTrackData.mEnergyLoss += fMC->Edep();
}
if (!(startHit | stopHit)) {
return kFALSE; // do nothing
}
if (startHit) {
mTrackData.mEnergyLoss = 0.;
fMC->TrackMomentum(mTrackData.mMomentumStart);
fMC->TrackPosition(mTrackData.mPositionStart);
mTrackData.mTrkStatusStart = status;
mTrackData.mHitStarted = true;
}
if (stopHit) {
TLorentzVector positionStop;
fMC->TrackPosition(positionStop);
addHit(currentTrackID(), sensorID, mTrackData.mPositionStart.Vect(), positionStop.Vect(),
mTrackData.mMomentumStart.Vect(), mTrackData.mMomentumStart.E(), positionStop.T(),
mTrackData.mEnergyLoss, mTrackData.mTrkStatusStart, status, fMC->TrackPid(), fMC->TrackLength());
mTrackData.mHitStarted = false;
}
return kTRUE;
}
int ExternalDetector::currentSensorID() const
{
const int volID = mCurrentVolume ? mCurrentVolume->getMCid() : -1;
auto it = mVolID2SensorID.find(volID);
return it == mVolID2SensorID.end() ? -1 : it->second;
}
int ExternalDetector::currentTrackID() const
{
return static_cast<o2::data::Stack*>(fMC->GetStack())->GetCurrentTrackNumber();
}
o2::ext::Hit* ExternalDetector::addHit(int trackID, int sensorID, const TVector3& startPos, const TVector3& endPos,
const TVector3& startMom, double startE, double endTime, double eLoss,
unsigned char startStatus, unsigned char endStatus, int pdg, float length)
{
mHits->emplace_back(trackID, sensorID, startPos, endPos, startMom, startE, endTime, eLoss,
startStatus, endStatus, pdg, length);
// register that this track left a hit in our detector (sets the hit bit on the MCTrack)
static_cast<o2::data::Stack*>(fMC->GetStack())->addHit(GetDetId());
return &(mHits->back());
}
void ExternalDetector::Register()
{
// Create a branch (named "<name>Hit") holding the produced hits.
if (FairRootManager::Instance()) {
FairRootManager::Instance()->RegisterAny(addNameTo("Hit").data(), mHits, kTRUE);
}
}
void ExternalDetector::Reset()
{
if (!o2::utils::ShmManager::Instance().isOperational()) {
mHits->clear();
}
}
void ExternalDetector::EndOfEvent()
{
// probe: report how often our sensitive volumes were stepped through and how many hits resulted
LOG(info) << "External detector " << GetName() << " EndOfEvent: " << mStepCount
<< " sensitive step(s) -> " << (mHits ? mHits->size() : 0) << " hit(s)";
mStepCount = 0;
Reset();
}
namespace
{
// Build a TGeoCombiTrans from an optional JSON "placement" object carrying
// "translation":[x,y,z] (cm) and/or "rotation_deg":[rx,ry,rz] (deg, applied X,Y,Z).
TGeoMatrix* makePlacementFromJSON(const rapidjson::Value& placement)
{
auto combi = new TGeoCombiTrans();
if (placement.HasMember("rotation_deg") && placement["rotation_deg"].IsArray()) {
const auto& r = placement["rotation_deg"];
if (r.Size() == 3) {
combi->RotateX(r[0].GetDouble());
combi->RotateY(r[1].GetDouble());
combi->RotateZ(r[2].GetDouble());
} else {
LOG(warning) << "ExternalDetector placement 'rotation_deg' must have 3 entries; ignoring";
}
}
if (placement.HasMember("translation") && placement["translation"].IsArray()) {
const auto& t = placement["translation"];
if (t.Size() == 3) {
combi->SetDx(t[0].GetDouble());
combi->SetDy(t[1].GetDouble());
combi->SetDz(t[2].GetDouble());
} else {
LOG(warning) << "ExternalDetector placement 'translation' must have 3 entries; ignoring";
}
}
return combi;
}
} // namespace
std::vector<ExternalDetector*> ExternalDetector::createFromJSON(const std::string& jsonfile)
{
std::vector<ExternalDetector*> result;
auto expanded = o2::utils::expandShellVarsInFileName(jsonfile);
std::ifstream fileStream(expanded, std::ios::in);
if (!fileStream.is_open()) {
LOG(error) << "Cannot open external geometry config file '" << expanded << "'";
return result;
}
rapidjson::IStreamWrapper isw(fileStream);
rapidjson::Document doc;
doc.ParseStream(isw);
if (doc.HasParseError()) {
LOG(error) << "Error parsing external geometry JSON '" << expanded << "': "
<< rapidjson::GetParseError_En(doc.GetParseError())
<< " (offset " << doc.GetErrorOffset() << ")";
return result;
}
// the array of sensitive external detectors is optional (the same file may only
// configure passive external modules)
if (!doc.HasMember("externalDetectors")) {
return result;
}
if (!doc["externalDetectors"].IsArray()) {
LOG(error) << "External geometry JSON '" << expanded << "': 'externalDetectors' must be an array";
return result;
}
auto getString = [](const rapidjson::Value& v, const char* key) -> std::string {
if (v.HasMember(key) && v[key].IsString()) {
return v[key].GetString();
}
return std::string();
};
for (const auto& entry : doc["externalDetectors"].GetArray()) {
if (!entry.IsObject()) {
LOG(error) << "Skipping non-object entry in 'externalDetectors'";
continue;
}
const auto name = getString(entry, "name");
if (name.empty()) {
LOG(error) << "Skipping external detector entry without 'name'";
continue;
}
ExternalDetectorOptions options;
options.root_macro_file = getString(entry, "macro");
options.anchor_volume = getString(entry, "anchor");
if (options.root_macro_file.empty() || options.anchor_volume.empty()) {
LOG(error) << "External detector '" << name << "' requires both 'macro' and 'anchor'; skipping";
continue;
}
if (entry.HasMember("sensitiveMedia") && entry["sensitiveMedia"].IsArray()) {
for (const auto& m : entry["sensitiveMedia"].GetArray()) {
if (m.IsString()) {
options.sensitiveMedia.emplace_back(m.GetString());
}
}
}
if (entry.HasMember("sensitiveVolumes") && entry["sensitiveVolumes"].IsArray()) {
for (const auto& v : entry["sensitiveVolumes"].GetArray()) {
if (v.IsString()) {
options.sensitiveVolumes.emplace_back(v.GetString());
}
}
}
if (options.sensitiveMedia.empty() && options.sensitiveVolumes.empty()) {
LOG(error) << "External detector '" << name
<< "' requires a non-empty 'sensitiveMedia' or 'sensitiveVolumes' array; skipping";
continue;
}
const auto detIDName = getString(entry, "detID");
if (!detIDName.empty()) {
const auto did = o2::detectors::DetID::nameToID(detIDName.c_str());
if (did < 0 || did >= o2::detectors::DetID::nDetectors) {
LOG(error) << "External detector '" << name << "': unknown detID '" << detIDName << "'; skipping";
continue;
}
options.detID = did;
}
if (entry.HasMember("placement") && entry["placement"].IsObject()) {
options.placement = makePlacementFromJSON(entry["placement"]);
}
// optional user-provided sensitive action (a ROOT macro). When absent, the built-in
// generic entrance/exit hit action is used.
options.sensitiveMacro = getString(entry, "sensitiveMacro");
options.sensitiveFunction = getString(entry, "sensitiveFunction");
auto title = getString(entry, "title");
if (title.empty()) {
title = name;
}
LOG(info) << "Configured external detector '" << name << "' from macro '" << options.root_macro_file
<< "' anchored to '" << options.anchor_volume << "', tied to DetID '"
<< o2::detectors::DetID::getName(options.detID) << "'";
result.push_back(new ExternalDetector(name.c_str(), title.c_str(), options));
}
return result;
}
} // namespace o2::ext
ClassImp(o2::ext::ExternalDetector);