DD4hep  1.38.0
Detector Description Toolkit for High Energy Physics
DetectorTools.cpp
Go to the documentation of this file.
1 //==========================================================================
2 // AIDA Detector description implementation
3 //--------------------------------------------------------------------------
4 // Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
5 // All rights reserved.
6 //
7 // For the licensing terms see $DD4hepINSTALL/LICENSE.
8 // For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
9 //
10 // Author : M.Frank
11 //
12 //==========================================================================
13 
14 // Framework include files
15 #define DETECTORTOOLS_CPP
17 #include <DD4hep/Printout.h>
18 #include <DD4hep/Detector.h>
20 
21 // C/C++ include files
22 #include <map>
23 #include <memory>
24 #include <set>
25 #include <stdexcept>
26 #include <sstream>
27 #include <string>
28 
29 // ROOT include files
30 #include <TGeoMatrix.h>
31 
33 namespace dd4hep {
34 
36 
40  namespace detail { namespace tools {
42  std::string elementPath(const PlacementPath& nodes, bool reverse);
46  void elementPath(DetElement elt, PlacementPath& nodes);
48  void elementPath(DetElement parent, DetElement element, PlacementPath& nodes);
50  bool findChild(PlacedVolume parent, PlacedVolume child, PlacementPath& path);
51 
52 
53  // Internal helper
54  static void makePlacementPath(DetElement element, PlacementPath det_nodes, PlacementPath& all_nodes);
55  }}
56 }
57 
58 using namespace dd4hep;
59 
60 namespace {
62  using ChildPaths = std::map<std::string, detail::tools::PlacementPath, std::less<>>;
64  thread_local std::unique_ptr<std::map<const TGeoNode*, ChildPaths>> s_pathCache;
65 
67  void collectPaths(TGeoNode* node, detail::tools::PlacementPath& branch,
68  std::set<std::string, std::less<>>& names, ChildPaths& paths) {
69  const Int_t num_daughters = node->GetNdaughters();
70  for( Int_t i = 0; i < num_daughters && !names.empty(); ++i ) { // First the daughters...
71  TGeoNode* daughter = node->GetDaughter(i);
72  auto name = daughter ? names.find(daughter->GetName()) : names.end();
73  if ( name != names.end() ) {
74  detail::tools::PlacementPath& path = paths[*name];
75  path.emplace_back(daughter);
76  path.insert(path.end(), branch.rbegin(), branch.rend());
77  names.erase(name);
78  }
79  }
80  for( Int_t i = 0; i < num_daughters && !names.empty(); ++i ) { // ...then their subtrees
81  if ( TGeoNode* daughter = node->GetDaughter(i) ) {
82  branch.emplace_back(daughter);
83  collectPaths(daughter, branch, names, paths);
84  branch.pop_back();
85  }
86  }
87  }
88 
90  bool cachedPath(DetElement parent, PlacedVolume parent_place, PlacedVolume child_place,
92  const char* name = child_place->GetName();
93  if ( 0 == ::strcmp(parent_place->GetName(), name) ) // Self match: left to findChildByName
94  return false;
95  auto [entry, is_new] = s_pathCache->try_emplace(parent_place.ptr());
96  if ( is_new ) {
97  std::set<std::string, std::less<>> names;
98  for( const auto& child : parent.children() ) {
99  PlacedVolume place = child.second.placement();
100  if ( place.isValid() && 0 != ::strcmp(place->GetName(), parent_place->GetName()) ) // self matches never come here
101  names.emplace(place->GetName());
102  }
104  collectPaths(parent_place.ptr(), branch, names, entry->second);
105  }
106  auto found = entry->second.find(name);
107  if ( found == entry->second.end() )
108  return false;
109  path.insert(path.end(), found->second.begin(), found->second.end());
110  return true;
111  }
112 }
113 
115  if ( !s_pathCache ) {
116  s_pathCache = std::make_unique<std::map<const TGeoNode*, ChildPaths>>();
117  m_owner = true;
118  }
119 }
120 
122  if ( m_owner )
123  s_pathCache.reset();
124 }
125 
128  if ( s_pathCache )
129  s_pathCache->clear();
130  if ( element.isValid() ) {
131  element->path.clear();
132  element->placementPath.clear();
133  element->key = 0;
134  element->level = -1;
135  for( const auto& child : element->children )
136  clearPathCaches(child.second);
137  }
138 }
139 
142  if ( parent.isValid() && child.isValid() ) {
143  if ( parent.ptr() == child.ptr() ) return true;
144  for(DetElement par=child; par.isValid(); par=par.parent()) {
145  if ( par.ptr() == parent.ptr() ) return true;
146  }
147  }
148  throw std::runtime_error("Search for parent detector element with invalid handles not allowed.");
149 }
150 
153  if ( parent.isValid() && child.isValid() ) {
154  // Check self
155  if ( parent.ptr() == child.ptr() ) {
156  path.emplace_back(child);
157  return true;
158  }
159  TIter next(parent->GetVolume()->GetNodes());
160  // Now check next layer children
161  for (TGeoNode *daughter = (TGeoNode*) next(); daughter; daughter = (TGeoNode*) next()) {
162  if ( daughter == child.ptr() ) {
163  path.emplace_back(daughter);
164  return true;
165  }
166  }
167  next.Reset();
168  // Finally crawl down the tree
169  for (TGeoNode *daughter = (TGeoNode*) next(); daughter; daughter = (TGeoNode*) next()) {
170  PlacementPath sub_path;
171  bool res = findChild(daughter, child, sub_path);
172  if (res) {
173  path.insert(path.end(), sub_path.begin(), sub_path.end());
174  path.emplace_back(daughter);
175  return res;
176  }
177  }
178  }
179  return false;
180 }
181 
183 static bool findChildByName(PlacedVolume parent, PlacedVolume child, detail::tools::PlacementPath& path) {
184  if ( parent.isValid() && child.isValid() ) {
185  // Check self
186  if ( 0 == ::strcmp(parent.ptr()->GetName(),child.ptr()->GetName()) ) {
187  path.emplace_back(child);
188  return true;
189  }
190  TIter next(parent->GetVolume()->GetNodes());
191  // Now check next layer children
192  for (TGeoNode *daughter = (TGeoNode*) next(); daughter; daughter = (TGeoNode*) next()) {
193  if ( 0 == ::strcmp(daughter->GetName(),child.ptr()->GetName()) ) {
194  path.emplace_back(daughter);
195  return true;
196  }
197  }
198  next.Reset();
199  // Finally crawl down the tree
200  for (TGeoNode *daughter = (TGeoNode*) next(); daughter; daughter = (TGeoNode*) next()) {
202  bool res = findChildByName(daughter, child, sub_path);
203  if (res) {
204  path.insert(path.end(), sub_path.begin(), sub_path.end());
205  path.emplace_back(daughter);
206  return res;
207  }
208  }
209  }
210  return false;
211 }
212 
215  for(DetElement par = element; par.isValid(); par = par.parent())
216  detectors.emplace_back(par);
217 }
218 
221  detectors.clear();
222  if ( parent.isValid() && child.isValid() ) {
223  if ( parent.ptr() == child.ptr() ) {
224  detectors.emplace_back(child);
225  return;
226  }
227  ElementPath elements;
228  for(DetElement par = child; par.isValid(); par = par.parent()) {
229  elements.emplace_back(par);
230  if ( par.ptr() == parent.ptr() ) {
231  detectors = elements;
232  return;
233  }
234  }
235  throw std::runtime_error(std::string("The detector element ")+parent.name()+std::string(" is no parent of ")+child.name());
236  }
237  throw std::runtime_error("Search for parent detector element with invalid handles not allowed.");
238 }
239 
242  if( element.isValid() ) {
243  if( !parent.isValid() ) {
244  parent = element.world();
245  }
246  for( DetElement par = element; par.isValid(); par = par.parent() ) {
247  PlacedVolume pv = par.placement();
248  if ( pv.isValid() ) {
249  det_nodes.emplace_back(pv);
250  }
251  if ( par.ptr() == parent.ptr() ) return;
252  }
253  throw std::runtime_error(("The detector element "+std::string(parent.name())+" is no parent of ")+element.name());
254  }
255  throw std::runtime_error("Cannot access element path [Invalid DetElement]");
256 }
257 
260  for(DetElement par = element; par.isValid(); par = par.parent()) {
261  PlacedVolume pv = par.placement();
262  if ( pv.isValid() ) {
263  det_nodes.emplace_back(pv);
264  }
265  }
266 }
267 
269 std::string detail::tools::elementPath(const PlacementPath& nodes, bool reverse) {
270  std::string path = "";
271  if ( reverse ) {
272  for(auto i=nodes.rbegin(); i != nodes.rend(); ++i)
273  path += "/" + std::string((*i).name());
274  }
275  else {
276  for(auto i=begin(nodes); i != end(nodes); ++i)
277  path += "/" + std::string((*i)->GetName());
278  }
279  return path;
280 }
281 
283 std::string detail::tools::elementPath(const ElementPath& nodes, bool reverse) {
284  std::string path = "";
285  if ( reverse ) {
286  for(ElementPath::const_reverse_iterator i=nodes.rbegin();i!=nodes.rend();++i)
287  path += "/" + std::string((*i)->GetName());
288  }
289  else {
290  for(ElementPath::const_iterator i=nodes.begin();i!=nodes.end();++i)
291  path += "/" + std::string((*i)->GetName());
292  }
293  return path;
294 }
295 
298  ElementPath nodes;
299  elementPath(element,nodes);
300  return elementPath(nodes);
301 }
302 
304 DetElement detail::tools::findElement(const Detector& description, const std::string& path) {
305  return findDaughterElement(description.world(),path);
306 }
307 
309 DetElement detail::tools::findDaughterElement(DetElement parent, const std::string& subpath) {
310  if ( parent.isValid() ) {
311  size_t idx = subpath.find('/',1);
312  if ( subpath[0] == '/' ) {
313  DetElement top = topElement(parent);
314  if ( idx == std::string::npos ) return top;
315  return findDaughterElement(top,subpath.substr(idx+1));
316  }
317  if ( idx == std::string::npos )
318  return parent.child(subpath);
319  std::string name = subpath.substr(0,idx);
320  DetElement node = parent.child(name);
321  if ( node.isValid() ) {
322  return findDaughterElement(node,subpath.substr(idx+1));
323  }
324  throw std::runtime_error("dd4hep: DetElement "+parent.path()+" has no child named:"+name+" [No such child]");
325  }
326  throw std::runtime_error("dd4hep: Cannot determine child with path "+subpath+" from invalid parent [invalid handle]");
327 }
328 
331  if ( child.isValid() ) {
332  if ( child.parent().isValid() )
333  return topElement(child.parent());
334  return child;
335  }
336  throw std::runtime_error("dd4hep: DetElement cannot determine top parent (world) [invalid handle]");
337 }
338 
339 static void detail::tools::makePlacementPath(DetElement element, PlacementPath det_nodes, PlacementPath& all_nodes) {
340  // The cache is only used for direct parent/child pairs; anything else (e.g. placement holes) uses findChildByName
341  DetElement elt = element;
342  for (size_t i = 0, n = det_nodes.size(); n > 0 && i < n-1; ++i, elt = elt.parent()) {
343  DetElement par = elt.parent();
344  bool found = s_pathCache && par.isValid() && par.placement().ptr() == det_nodes[i + 1].ptr()
345  && cachedPath(par, det_nodes[i + 1], det_nodes[i], all_nodes);
346  if (!found && !findChildByName(det_nodes[i + 1], det_nodes[i], all_nodes)) {
347  throw std::runtime_error("dd4hep: DetElement cannot determine placement path of "
348  + std::string(det_nodes[i].name()) + " [internal error]");
349  }
350  }
351  if ( det_nodes.size() > 0 ) {
352  all_nodes.emplace_back(det_nodes.back());
353  }
354 }
355 
358  PlacementPath det_nodes;
359  elementPath(element,det_nodes);
360  makePlacementPath(element, std::move(det_nodes), all_nodes);
361 }
362 
365  PlacementPath det_nodes;
366  elementPath(parent,element,det_nodes);
367  makePlacementPath(element, std::move(det_nodes), all_nodes);
368 }
369 
372  PlacementPath path;
373  placementPath(element,path);
374  return placementPath(std::move(path));
375 }
376 
378 std::string detail::tools::placementPath(const PlacementPath& nodes, bool reverse) {
379  std::string path = "";
380  if ( reverse ) {
381  for(PlacementPath::const_reverse_iterator i=nodes.rbegin();i!=nodes.rend();++i)
382  path += "/" + std::string((*i)->GetName());
383  }
384  else {
385  for(PlacementPath::const_iterator i=nodes.begin();i!=nodes.end();++i)
386  path += "/" + std::string((*i)->GetName());
387  }
388  return path;
389 }
390 
392 std::string detail::tools::placementPath(const std::vector<const TGeoNode*>& nodes, bool reverse) {
393  std::string path = "";
394  if ( reverse ) {
395  for(std::vector<const TGeoNode*>::const_reverse_iterator i=nodes.rbegin();i!=nodes.rend();++i)
396  path += "/" + std::string((*i)->GetName());
397  return path;
398  }
399  for( const auto* n : nodes )
400  path += "/" + std::string(n->GetName());
401  return path;
402 }
403 
405 void detail::tools::placementTrafo(const PlacementPath& nodes, bool inverse, TGeoHMatrix*& mat) {
406  if ( !mat ) mat = new TGeoHMatrix(*gGeoIdentity);
407  placementTrafo(nodes,inverse,*mat);
408 }
409 
411 void detail::tools::placementTrafo(const PlacementPath& nodes, bool inverse, TGeoHMatrix& mat) {
412  mat = *gGeoIdentity;
413  if (nodes.size() > 0) {
414  for (size_t i = 0, n=nodes.size(); n>0 && i < n-1; ++i) {
415  const PlacedVolume& p = nodes[i];
416  mat.MultiplyLeft(p->GetMatrix());
417  }
418  if ( inverse ) mat = mat.Inverse();
419  }
420 }
421 
423 PlacedVolume detail::tools::findNode(PlacedVolume top_place, const std::string& place) {
424  TGeoNode* top = top_place.ptr();
425  const char* path = place.c_str();
426  // Check if a geometry path is valid without changing the state of the navigator.
427  Int_t length = strlen(path);
428  if (!length) return 0;
429  TString spath = path;
430  TGeoVolume *vol;
431  // Check first occurance of a '/'
432  Int_t ind1 = spath.Index("/");
433  if (ind1<0) {
434  // No '/' so we check directly the path against the name of the top
435  if ( strcmp(path,top->GetName()) ) return 0;
436  return top;
437  }
438  Int_t ind2 = ind1;
439  Bool_t end = kFALSE;
440  if (ind1>0) ind1 = -1; // no trailing '/'
441  else ind2 = spath.Index("/", ind1+1);
442 
443  if (ind2<0) ind2 = length;
444  TString name(spath(ind1+1, ind2-ind1-1));
445  if ( name == top->GetName() ) {
446  if (ind2>=length-1) return top;
447  ind1 = ind2;
448  }
449  else {
450  return 0;
451  }
452  TGeoNode *node = top;
453  // Deeper than just top level
454  while (!end) {
455  ind2 = spath.Index("/", ind1+1);
456  if (ind2<0) {
457  ind2 = length;
458  end = kTRUE;
459  }
460  vol = node->GetVolume();
461  name = spath(ind1+1, ind2-ind1-1);
462  node = vol->GetNode(name.Data());
463  if (!node)
464  return 0;
465  else if (ind2>=length-1)
466  return node;
467  ind1 = ind2;
468  }
469  return node;
470 }
471 
474  std::stringstream log;
475  for( const auto& v : ids )
476  log << v.first << "=" << v.second << "; ";
477  return log.str();
478 }
479 
481 std::string detail::tools::toString(const IDDescriptor& dsc, const PlacedVolume::VolIDs& ids, VolumeID code) {
482  std::stringstream log;
483  for( const auto& id : ids ) {
484  const BitFieldElement* f = dsc.field(id.first);
485  VolumeID value = f->value(code);
486  log << id.first << "=" << id.second << "," << value << " [" << f->offset() << "," << f->width() << "] ";
487  }
488  return log.str();
489 }
490 
492 std::vector<std::string> detail::tools::pathElements(const std::string& path) {
493  std::vector<std::string> result;
494  if ( !path.empty() ) {
495  std::string tmp = path[0]=='/' ? path.substr(1) : path;
496  for(size_t idx=tmp.find('/'); idx != std::string::npos; idx=tmp.find('/')) {
497  std::string val = tmp.substr(0,idx);
498  result.emplace_back(val);
499  tmp = tmp.length()>idx ? tmp.substr(idx+1) : std::string();
500  }
501  if ( !tmp.empty() ) {
502  result.emplace_back(tmp);
503  }
504  }
505  return result;
506 }
dd4hep::DetElement::children
const Children & children() const
Access to the list of children.
Definition: DetElement.cpp:248
dd4hep::DetElement::path
const std::string & path() const
Path of the detector element (not necessarily identical to placement path!)
Definition: DetElement.cpp:178
dd4hep::DDSegmentation::BitFieldElement::offset
unsigned offset() const
Definition: BitFieldCoder.h:63
dd4hep::Detector::world
virtual DetElement world() const =0
Return reference to the top-most (world) detector element.
dd4hep::DDSegmentation::BitFieldElement
Helper class for BitFieldCoder that corresponds to one field value.
Definition: BitFieldCoder.h:31
dd4hep::DetElement::key
unsigned int key() const
Access hash key of this detector element (Only valid once geometry is closed!)
Definition: DetElement.cpp:154
dd4hep::detail::tools::ElementPath
std::vector< DetElement > ElementPath
Definition: DetectorTools.h:38
v
View * v
Definition: MultiView.cpp:28
dd4hep::DetElement::parent
DetElement parent() const
Access to the detector elements's parent.
Definition: DetElement.cpp:280
Detector.h
dd4hep::IDDescriptor::field
const BitFieldElement * field(const std::string &field_name) const
Get the field descriptor of one field by name.
Definition: IDDescriptor.cpp:96
dd4hep::PlacedVolume
Handle class holding a placed volume (also called physical volume)
Definition: Volumes.h:164
dd4hep::detail::tools::PlacementPathCache::~PlacementPathCache
~PlacementPathCache()
Definition: DetectorTools.cpp:121
dd4hep::DetElement::placement
PlacedVolume placement() const
Access to the physical volume of this detector element.
Definition: DetElement.cpp:362
dd4hep::detail::tools::placementPath
std::string placementPath(DetElement element)
Assemble the placement path from a given detector element to the world volume.
Definition: DetectorTools.cpp:371
dd4hep::IDDescriptor
Class implementing the ID encoding of the detector response.
Definition: IDDescriptor.h:36
dd4hep::DDSegmentation::BitFieldElement::value
FieldID value(CellID bitfield) const
calculate this field's value given an external 64 bit bitmap
Definition: BitFieldCoder.cpp:56
dd4hep::Handle::isValid
bool isValid() const
Check the validity of the object held by the handle.
Definition: Handle.h:126
DetectorInterna.h
dd4hep::Handle::name
const char * name() const
Access the object name (or "" if not supported by the object)
dd4hep::detail::tools::findDaughterElement
DetElement findDaughterElement(DetElement parent, const std::string &subpath)
Find DetElement as child of a parent by its relative or absolute path.
Definition: DetectorTools.cpp:309
dd4hep::detail::tools::PlacementPathCache::PlacementPathCache
PlacementPathCache()
Definition: DetectorTools.cpp:114
dd4hep::detail::tools::findElement
DetElement findElement(const Detector &description, const std::string &path)
Find DetElement as child of the top level volume by its absolute path.
Definition: DetectorTools.cpp:304
dd4hep::detail::tools::placementTrafo
void placementTrafo(const PlacementPath &nodes, bool inverse, TGeoHMatrix *&mat)
Update cached matrix to transform to positions to an upper level Placement.
Definition: DetectorTools.cpp:405
dd4hep::DetElement
Handle class describing a detector element.
Definition: DetElement.h:187
dd4hep::PlacedVolumeExtension::VolIDs
Volume ID container.
Definition: Volumes.h:89
dd4hep::detail::tools::findChild
bool findChild(PlacedVolume parent, PlacedVolume child, PlacementPath &path)
Find Child of PlacedVolume and assemble on the fly the path of PlacedVolumes.
Definition: DetectorTools.cpp:152
DetectorTools.h
dd4hep::DDSegmentation::BitFieldElement::width
unsigned width() const
Definition: BitFieldCoder.h:66
dd4hep::DetElement::placementPath
const std::string & placementPath() const
Access to the full path to the placed object.
Definition: DetElement.cpp:116
dd4hep::DetElement::level
int level() const
Access the hierarchical level of the detector element (Only valid once geometry is closed!...
Definition: DetElement.cpp:166
ElementPath
detail::tools::ElementPath ElementPath
Definition: DetectorInterna.cpp:30
dd4hep::detail::tools::isParentElement
bool isParentElement(DetElement parent, DetElement child)
Find path between the child element and the parent element.
Definition: DetectorTools.cpp:141
detectors
DetectorMap detectors
Definition: AlignmentsCalculator.cpp:79
dd4hep::detail::tools::findNode
PlacedVolume findNode(PlacedVolume top_place, const std::string &place)
Find a given node in the hierarchy starting from the top node (absolute placement!...
Definition: DetectorTools.cpp:423
dd4hep::detail::tools::pathElements
std::vector< std::string > pathElements(const std::string &path)
Extract all the path elements from a path.
Definition: DetectorTools.cpp:492
VolumeID
dd4hep::DDSegmentation::VolumeID VolumeID
Definition: SegmentationDictionary.h:50
dd4hep::detail::tools::elementPath
std::string elementPath(DetElement element)
Assemble the path of a particular detector element.
Definition: DetectorTools.cpp:297
dd4hep::Handle::ptr
T * ptr() const
Access to the held object.
Definition: Handle.h:151
dd4hep::detail::tools::topElement
DetElement topElement(DetElement child)
Determine top level element (=world) for any element walking up the detector element tree.
Definition: DetectorTools.cpp:330
dd4hep
Namespace for the AIDA detector description toolkit.
Definition: AlignmentsCalib.h:28
dd4hep::DetElement::child
DetElement child(const std::string &name) const
Access to individual children by name.
Definition: DetElement.cpp:253
dd4hep::detail::tools::toString
std::string toString(const PlacedVolume::VolIDs &ids)
Convert VolumeID to string.
Definition: DetectorTools.cpp:473
dd4hep::detail::tools::PlacementPath
std::vector< PlacedVolume > PlacementPath
Definition: DetectorTools.h:39
dd4hep::Detector
The main interface to the dd4hep detector description package.
Definition: Detector.h:89
dd4hep::detail::tools::PlacementPathCache::m_owner
bool m_owner
Definition: DetectorTools.h:73
dd4hep::detail::tools::clearPathCaches
void clearPathCaches(DetElement element)
Clear the placement path cache of this thread and the paths cached by the detector element and its ch...
Definition: DetectorTools.cpp:127
PlacementPath
detail::tools::PlacementPath PlacementPath
Definition: DetectorInterna.cpp:29
dd4hep::DetElement::world
DetElement world() const
Access to the world object. Only possible once the geometry is closed.
Definition: DetElement.cpp:286
Printout.h