-
Notifications
You must be signed in to change notification settings - Fork 91
/
Compact2Objects.cpp
1649 lines (1566 loc) · 65.8 KB
/
Compact2Objects.cpp
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//==========================================================================
// AIDA Detector description implementation
//--------------------------------------------------------------------------
// Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
// All rights reserved.
//
// For the licensing terms see $DD4hepINSTALL/LICENSE.
// For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
//
// Author : M.Frank
//
//==========================================================================
//
// Main conversion operations for the compact notation.
// - Create elements, materials, etc.
// - Calls detector construction factories.
//
//==========================================================================
//
// Framework includes
#include <DD4hep/DetFactoryHelper.h>
#include <DD4hep/DetectorTools.h>
#include <DD4hep/MatrixHelpers.h>
#include <DD4hep/PropertyTable.h>
#include <DD4hep/OpticalSurfaces.h>
#include <DD4hep/OpticalSurfaceManager.h>
#include <DD4hep/IDDescriptor.h>
#include <DD4hep/DD4hepUnits.h>
#include <DD4hep/FieldTypes.h>
#include <DD4hep/Printout.h>
#include <DD4hep/Factories.h>
#include <DD4hep/Plugins.h>
#include <DD4hep/detail/SegmentationsInterna.h>
#include <DD4hep/detail/DetectorInterna.h>
#include <DD4hep/detail/ObjectsInterna.h>
#include <XML/DocumentHandler.h>
#include <XML/Utilities.h>
// Root/TGeo include files
#include <TGeoManager.h>
#include <TGeoMaterial.h>
#if ROOT_VERSION_CODE >= ROOT_VERSION(6,12,0)
#include <TGeoPhysicalConstants.h>
#endif
#if ROOT_VERSION_CODE >= ROOT_VERSION(6,17,0)
#include <TGDMLMatrix.h>
#endif
#include <TMath.h>
// C/C++ include files
#include <climits>
#include <iostream>
#include <iomanip>
#include <set>
using namespace std;
using namespace dd4hep;
/// Namespace for the AIDA detector description toolkit
namespace dd4hep {
class Debug;
class World;
class Isotope;
class Plugin;
class Compact;
class Includes;
class IncludeFile;
class Property;
class XMLFile;
class JsonFile;
class PropertyConstant;
class Parallelworld_Volume;
class DetElementInclude;
class STD_Conditions;
/// Converter instances implemented in this compilation unit
template <> void Converter<Debug>::operator()(xml_h element) const;
template <> void Converter<World>::operator()(xml_h element) const;
template <> void Converter<Plugin>::operator()(xml_h element) const;
template <> void Converter<Constant>::operator()(xml_h element) const;
template <> void Converter<Material>::operator()(xml_h element) const;
template <> void Converter<Atom>::operator()(xml_h element) const;
template <> void Converter<Isotope>::operator()(xml_h element) const;
template <> void Converter<VisAttr>::operator()(xml_h element) const;
template <> void Converter<Region>::operator()(xml_h element) const;
template <> void Converter<Readout>::operator()(xml_h element) const;
template <> void Converter<Segmentation>::operator()(xml_h element) const;
template <> void Converter<LimitSet>::operator()(xml_h element) const;
template <> void Converter<Property>::operator()(xml_h element) const;
template <> void Converter<CartesianField>::operator()(xml_h element) const;
template <> void Converter<SensitiveDetector>::operator()(xml_h element) const;
#if ROOT_VERSION_CODE >= ROOT_VERSION(6,17,0)
template <> void Converter<OpticalSurface>::operator()(xml_h element) const;
template <> void Converter<PropertyTable>::operator()(xml_h element) const;
template <> void Converter<PropertyConstant>::operator()(xml_h element) const;
#endif
template <> void Converter<DetElement>::operator()(xml_h element) const;
template <> void Converter<STD_Conditions>::operator()(xml_h element) const;
template <> void Converter<IncludeFile>::operator()(xml_h element) const;
template <> void Converter<JsonFile>::operator()(xml_h element) const;
template <> void Converter<XMLFile>::operator()(xml_h element) const;
template <> void Converter<Header>::operator()(xml_h element) const;
template <> void Converter<DetElementInclude>::operator()(xml_h element) const;
template <> void Converter<Parallelworld_Volume>::operator()(xml_h element) const;
template <> void Converter<Compact>::operator()(xml_h element) const;
}
namespace {
static UInt_t unique_mat_id = 0xAFFEFEED;
void throw_print(const string& msg) {
printout(ERROR, "Compact", msg.c_str());
throw runtime_error(msg);
}
class DebugOptions {
public:
bool readout = false;
bool regions = false;
bool limits = false;
bool visattr = false;
bool isotopes = false;
bool elements = false;
bool materials = false;
bool segmentation = false;
bool constants = false;
bool includes = false;
bool matrix = false;
bool surface = false;
} s_debug;
}
static Ref_t create_ConstantField(Detector& /* description */, xml_h e) {
CartesianField obj;
xml_comp_t field(e), strength(e.child(_U(strength)));
string t = e.attr<string>(_U(field));
ConstantField* ptr = new ConstantField();
ptr->type = ::toupper(t[0]) == 'E' ? CartesianField::ELECTRIC : CartesianField::MAGNETIC;
ptr->direction.SetX(strength.x());
ptr->direction.SetY(strength.y());
ptr->direction.SetZ(strength.z());
obj.assign(ptr, field.nameStr(), field.typeStr());
return obj;
}
DECLARE_XMLELEMENT(ConstantField,create_ConstantField)
static Ref_t create_SolenoidField(Detector& description, xml_h e) {
xml_comp_t c(e);
bool has_inner_radius = c.hasAttr(_U(inner_radius));
bool has_outer_radius = c.hasAttr(_U(outer_radius));
if (!has_inner_radius && !has_outer_radius) {
throw_print("Compact2Objects[ERROR]: For a solenoidal field at least one of the "
" xml attributes inner_radius of outer_radius MUST be set.");
}
CartesianField obj;
SolenoidField* ptr = new SolenoidField();
//
// This logic is a bit weird, but has its origin in the compact syntax:
// If no "inner_radius" is given, the "outer_radius" IS the "inner_radius"
// and the "outer_radius" is given by one side of the world volume's box
//
if (has_inner_radius && has_outer_radius) {
ptr->innerRadius = c.attr<double>(_U(inner_radius));
ptr->outerRadius = c.attr<double>(_U(outer_radius));
}
else if (has_inner_radius) {
Box box = description.worldVolume().solid();
ptr->innerRadius = c.attr<double>(_U(inner_radius));
ptr->outerRadius = box.x();
}
else if (has_outer_radius) {
Box box = description.worldVolume().solid();
ptr->innerRadius = c.attr<double>(_U(outer_radius));
ptr->outerRadius = box.x();
}
if (c.hasAttr(_U(inner_field)))
ptr->innerField = c.attr<double>(_U(inner_field));
if (c.hasAttr(_U(outer_field)))
ptr->outerField = c.attr<double>(_U(outer_field));
if (c.hasAttr(_U(zmax)))
ptr->maxZ = c.attr<double>(_U(zmax));
else
ptr->maxZ = description.constant<double>("world_side");
if (c.hasAttr(_U(zmin)))
ptr->minZ = c.attr<double>(_U(zmin));
else
ptr->minZ = -ptr->maxZ;
obj.assign(ptr, c.nameStr(), c.typeStr());
return obj;
}
DECLARE_XMLELEMENT(SolenoidMagnet,create_SolenoidField)
// This is the plugin required for slic: note the different name
DECLARE_XMLELEMENT(solenoid,create_SolenoidField)
static Ref_t create_DipoleField(Detector& /* description */, xml_h e) {
xml_comp_t c(e);
CartesianField obj;
DipoleField* ptr = new DipoleField();
double lunit = c.hasAttr(_U(lunit)) ? c.attr<double>(_U(lunit)) : 1.0;
double funit = c.hasAttr(_U(funit)) ? c.attr<double>(_U(funit)) : 1.0;
double val, mult = funit;
if (c.hasAttr(_U(zmin)))
ptr->zmin = _multiply<double>(c.attr<string>(_U(zmin)), lunit);
if (c.hasAttr(_U(zmax)))
ptr->zmax = _multiply<double>(c.attr<string>(_U(zmax)), lunit);
if (c.hasAttr(_U(rmax)))
ptr->rmax = _multiply<double>(c.attr<string>(_U(rmax)), lunit);
for (xml_coll_t coll(c, _U(dipole_coeff)); coll; ++coll, mult /= lunit) {
xml_dim_t coeff = coll;
if ( coeff.hasAttr(_U(value)) )
val = coll.attr<double>(_U(value)) * mult;
else if ( coeff.hasAttr(_U(coefficient)) )
val = coeff.coefficient() * mult;
else
val = _multiply<double>(coll.text(), mult);
ptr->coefficents.emplace_back(val);
}
obj.assign(ptr, c.nameStr(), c.typeStr());
return obj;
}
DECLARE_XMLELEMENT(DipoleMagnet,create_DipoleField)
static Ref_t create_MultipoleField(Detector& description, xml_h e) {
xml_dim_t c(e), child;
CartesianField obj;
MultipoleField* ptr = new MultipoleField();
double lunit = c.hasAttr(_U(lunit)) ? c.attr<double>(_U(lunit)) : 1.0;
double funit = c.hasAttr(_U(funit)) ? c.attr<double>(_U(funit)) : 1.0;
double val, mult = funit, bz = 0.0;
RotationZYX rot;
Position pos;
if (c.hasAttr(_U(Z))) bz = c.Z() * funit;
if ((child = c.child(_U(position), false))) { // Position is not mandatory!
pos.SetXYZ(child.x(), child.y(), child.z());
}
if ((child = c.child(_U(rotation), false))) { // Rotation is not mandatory
rot.SetComponents(child.z(), child.y(), child.x());
}
if ((child = c.child(_U(shape), false))) { // Shape is not mandatory
string type = child.typeStr();
ptr->volume = xml::createShape(description, type, child);
}
ptr->B_z = bz;
ptr->transform = Transform3D(rot,pos).Inverse();
for (xml_coll_t coll(c, _U(coefficient)); coll; ++coll, mult /= lunit) {
xml_dim_t coeff = coll;
if ( coll.hasAttr(_U(value)) )
val = coll.attr<double>(_U(value)) * mult;
else
val = coeff.coefficient(0.0) * mult;
ptr->coefficents.emplace_back(val);
val = coeff.skew(0.0) * mult;
ptr->skews.emplace_back(val);
}
obj.assign(ptr, c.nameStr(), c.typeStr());
return obj;
}
DECLARE_XMLELEMENT(MultipoleMagnet,create_MultipoleField)
static long load_Compact(Detector& description, xml_h element) {
Converter<Compact>converter(description);
converter(element);
return 1;
}
DECLARE_XML_DOC_READER(lccdd,load_Compact)
DECLARE_XML_DOC_READER(compact,load_Compact)
/** Convert parser debug flags.
*/
template <> void Converter<Debug>::operator()(xml_h e) const {
for (xml_coll_t coll(e, _U(type)); coll; ++coll) {
int val = coll.attr<int>(_U(value));
string nam = coll.attr<string>(_U(name));
if ( nam.substr(0,6) == "isotop" ) s_debug.isotopes = (0 != val);
else if ( nam.substr(0,6) == "elemen" ) s_debug.elements = (0 != val);
else if ( nam.substr(0,6) == "materi" ) s_debug.materials = (0 != val);
else if ( nam.substr(0,6) == "visatt" ) s_debug.visattr = (0 != val);
else if ( nam.substr(0,6) == "region" ) s_debug.regions = (0 != val);
else if ( nam.substr(0,6) == "readou" ) s_debug.readout = (0 != val);
else if ( nam.substr(0,6) == "limits" ) s_debug.limits = (0 != val);
else if ( nam.substr(0,6) == "segmen" ) s_debug.segmentation = (0 != val);
else if ( nam.substr(0,6) == "consta" ) s_debug.constants = (0 != val);
else if ( nam.substr(0,6) == "define" ) s_debug.constants = (0 != val);
else if ( nam.substr(0,6) == "includ" ) s_debug.includes = (0 != val);
else if ( nam.substr(0,6) == "matrix" ) s_debug.matrix = (0 != val);
else if ( nam.substr(0,6) == "surfac" ) s_debug.surface = (0 != val);
}
}
/** Convert/execute plugin objects from the xml (plugins)
*
*
*/
template <> void Converter<Plugin>::operator()(xml_h e) const {
xml_comp_t plugin(e);
vector<char*> argv;
vector<string> arguments;
string name = plugin.nameStr();
string type = "default";
xml_attr_t typ_attr = e.attr_nothrow(_U(type));
if ( typ_attr ) {
type = e.attr<string>(_U(type));
}
if ( type == "default" ) {
for (xml_coll_t coll(e, _U(arg)); coll; ++coll) {
string val = coll.attr<string>(_U(value));
arguments.emplace_back(val);
}
for (xml_coll_t coll(e, _U(argument)); coll; ++coll) {
string val = coll.attr<string>(_U(value));
arguments.emplace_back(val);
}
for(vector<string>::iterator i=arguments.begin(); i!=arguments.end(); ++i)
argv.emplace_back(&((*i)[0]));
description.apply(name.c_str(),int(argv.size()), &argv[0]);
return;
}
// Call a custom plugin taking the xml element as an argument
long result = PluginService::Create<long>(name, &description, &e);
if (0 == result) {
PluginDebug dbg;
result = PluginService::Create<long>(name, &description, &e);
if ( 0 == result ) {
except("Compact","++ Failed to locate plugin %s - no factory: %s",
name.c_str(), dbg.missingFactory(name).c_str());
}
}
result = *(long*) result;
if (result != 1) {
except("Compact","++ Failed to execute plugin %s", name.c_str());
}
}
/** Convert compact constant objects (defines)
*
*
*/
template <> void Converter<Constant>::operator()(xml_h e) const {
if ( e.tag() != "include" ) {
xml_ref_t constant(e);
string nam = constant.attr<string>(_U(name));
string val = constant.attr<string>(_U(value));
string typ = constant.hasAttr(_U(type)) ? constant.attr<string>(_U(type)) : "number";
Constant c(nam, val, typ);
_toDictionary(nam, val, typ);
description.addConstant(c);
if ( s_debug.constants ) {
printout(ALWAYS, "Compact",
"++ Converting constant %-16s = %-32s [%s]", nam.c_str(), val.c_str(), typ.c_str());
}
return;
}
xml::DocumentHolder doc(xml::DocumentHandler().load(e, e.attr_value(_U(ref))));
if ( s_debug.includes ) {
printout(ALWAYS, "Compact","++ Processing xml document %s.",doc.uri().c_str());
}
xml_h root = doc.root();
xml_coll_t(root, _U(define)).for_each(_U(constant), Converter<Constant>(description));
xml_coll_t(root, _U(constant)).for_each(Converter<Constant>(description));
}
/** Convert compact constant objects (defines)
*
*
*/
template <> void Converter<Header>::operator()(xml_h e) const {
xml_comp_t c(e);
Header h(e.attr<string>(_U(name)), e.attr<string>(_U(title), "Undefined"));
h.setUrl(e.attr<string>(_U(url), "Undefined"));
h.setAuthor(e.attr<string>(_U(author), "Undefined"));
h.setStatus(e.attr<string>(_U(status), "development"));
h.setVersion(e.attr<string>(_U(version), "Undefined"));
h.setComment(e.hasChild(_U(comment)) ? e.child(_U(comment)).text() : "No Comment");
description.setHeader(h);
}
/** Convert compact material/element description objects
*
* Materials:
* <material name="Air">
* <D type="density" unit="g/cm3" value="0.0012"/>
* <fraction n="0.754" ref="N"/>
* <fraction n="0.234" ref="O"/>
* <fraction n="0.012" ref="Ar"/>
* </material>
*
* Elements:
* <element Z="29" formula="Cu" name="Cu" >
* <atom type="A" unit="g/mol" value="63.5456" />
* </element>
*
*/
template <> void Converter<Material>::operator()(xml_h e) const {
xml_ref_t x_mat(e);
TGeoManager& mgr = description.manager();
xml_tag_t mname = x_mat.name();
const char* matname = mname.c_str();
TGeoElementTable* table = mgr.GetElementTable();
TGeoMaterial* mat = mgr.GetMaterial(matname);
TGeoMixture* mix = dynamic_cast<TGeoMixture*>(mat);
xml_coll_t fractions (x_mat, _U(fraction));
xml_coll_t composites(x_mat, _U(composite));
if (0 == mat) {
TGeoMaterial* comp_mat;
TGeoElement* comp_elt;
xml_h density = x_mat.child(_U(D), false);
double dens_val = density.ptr() ? density.attr<double>(_U(value)) : 0.0;
double dens_unit = 1.0;
if ( !density.ptr() ) {
throw_print("Compact2Objects[ERROR]: material without density tag ( <D unit=\"g/cm3\" value=\"..\"/> ) provided: "
+ string( matname ) ) ;
}
if ( density.hasAttr(_U(unit)) ) {
dens_unit = density.attr<double>(_U(unit))/xml::_toDouble(_Unicode(gram/cm3));
}
if ( dens_unit != 1.0 ) {
dens_val *= dens_unit;
printout(s_debug.materials ? ALWAYS : DEBUG, "Compact","Density unit: %.3f [%s] raw: %.3f normalized: %.3f ",
dens_unit, density.attr<string>(_U(unit)).c_str(), dens_val, (dens_val*dens_unit));
}
mat = mix = new TGeoMixture(matname, composites.size(), dens_val);
size_t ifrac = 0;
vector<double> composite_fractions;
double composite_fractions_total = 0.0;
for (composites.reset(); composites; ++composites) {
string nam = composites.attr<string>(_U(ref));
double fraction = composites.attr<double>(_U(n));
if (0 != (comp_mat = mgr.GetMaterial(nam.c_str())))
fraction *= comp_mat->GetA();
else if (0 != (comp_elt = table->FindElement(nam.c_str())))
fraction *= comp_elt->A();
else
except("Compact2Objects","Converting material: %s Element missing: %s",mname.c_str(),nam.c_str());
composite_fractions_total += fraction;
composite_fractions.emplace_back(fraction);
}
for (composites.reset(), ifrac=0; composites; ++composites, ++ifrac) {
string nam = composites.attr<string>(_U(ref));
double fraction = composite_fractions[ifrac]/composite_fractions_total;
if (0 != (comp_mat = mgr.GetMaterial(nam.c_str())))
mix->AddElement(comp_mat, fraction);
else if (0 != (comp_elt = table->FindElement(nam.c_str())))
mix->AddElement(comp_elt, fraction);
}
for (fractions.reset(); fractions; ++fractions) {
string nam = fractions.attr<string>(_U(ref));
double fraction = fractions.attr<double>(_U(n));
if (0 != (comp_mat = mgr.GetMaterial(nam.c_str())))
mix->AddElement(comp_mat, fraction);
else if (0 != (comp_elt = table->FindElement(nam.c_str())))
mix->AddElement(comp_elt, fraction);
else
throw_print("Compact2Objects[ERROR]: Converting material:" + mname + " Element missing: " + nam);
}
xml_h temperature = x_mat.child(_U(T), false);
double temp_val = description.stdConditions().temperature;
if ( temperature.ptr() ) {
double temp_unit = _toDouble("kelvin");
if ( temperature.hasAttr(_U(unit)) )
temp_unit = temperature.attr<double>(_U(unit));
temp_val = temperature.attr<double>(_U(value)) * temp_unit;
}
xml_h pressure = x_mat.child(_U(P), false);
double pressure_val = description.stdConditions().pressure;
if ( pressure.ptr() ) {
double pressure_unit = _toDouble("pascal");
if ( pressure.hasAttr(_U(unit)) )
pressure_unit = pressure.attr<double>(_U(unit));
pressure_val = pressure.attr<double>(_U(value)) * pressure_unit;
}
#if 0
printout(s_debug.materials ? ALWAYS : DEBUG, "Compact",
"++ ROOT raw temperature and pressure: %.3g %.3g",
mat->GetTemperature(),mat->GetPressure());
#endif
mat->SetTemperature(temp_val);
mat->SetPressure(pressure_val);
printout(s_debug.materials ? ALWAYS : DEBUG, "Compact",
"++ Converting material %-16s Density: %9.7g Temperature:%9.7g [K] Pressure:%9.7g [hPa].",
matname, dens_val, temp_val/dd4hep::kelvin, pressure_val/dd4hep::pascal/100.0);
mix->SetRadLen(0e0);
#if ROOT_VERSION_CODE >= ROOT_VERSION(6,12,0)
mix->ComputeDerivedQuantities();
#endif
#if ROOT_VERSION_CODE >= ROOT_VERSION(6,17,0)
/// In case there were material properties specified: convert them here
for(xml_coll_t properties(x_mat, _U(constant)); properties; ++properties) {
xml_elt_t p = properties;
if ( p.hasAttr(_U(ref)) ) {
bool err = kFALSE;
string ref = p.attr<string>(_U(ref));
mgr.GetProperty(ref.c_str(), &err); /// Check existence
if ( err == kFALSE ) {
string prop_nam = p.attr<string>(_U(name));
mat->AddConstProperty(prop_nam.c_str(), ref.c_str());
printout(s_debug.materials ? ALWAYS : DEBUG, "Compact",
"++ material %-16s add constant property: %s -> %s.",
mat->GetName(), prop_nam.c_str(), ref.c_str());
continue;
}
// ERROR
throw_print("Compact2Objects[ERROR]: Converting material:" + mname + " ConstProperty missing in TGeoManager: " + ref);
}
else if ( p.hasAttr(_U(value)) ) {
stringstream str;
string ref, prop_nam = p.attr<string>(_U(name));
str << prop_nam << "_" << (void*)mat;
ref = str.str();
mgr.AddProperty(ref.c_str(), p.attr<double>(_U(value))); /// Check existence
mat->AddConstProperty(prop_nam.c_str(), ref.c_str());
printout(s_debug.materials ? ALWAYS : DEBUG, "Compact",
"++ material %-16s add constant property: %s -> %s.",
mat->GetName(), prop_nam.c_str(), ref.c_str());
}
else if ( p.hasAttr(_U(option)) ) {
string prop_nam = p.attr<string>(_U(name));
string prop_typ = p.attr<string>(_U(option));
mat->AddConstProperty(prop_nam.c_str(), prop_typ.c_str());
printout(s_debug.materials ? ALWAYS : DEBUG, "Compact",
"++ material %-16s add constant property: %s -> %s.",
mat->GetName(), prop_nam.c_str(), prop_typ.c_str());
}
}
/// In case there were material properties specified: convert them here
for(xml_coll_t properties(x_mat, _U(property)); properties; ++properties) {
xml_elt_t p = properties;
if ( p.hasAttr(_U(ref)) ) {
string ref = p.attr<string>(_U(ref));
TGDMLMatrix* gdmlMat = mgr.GetGDMLMatrix(ref.c_str());
if ( gdmlMat ) {
string prop_nam = p.attr<string>(_U(name));
mat->AddProperty(prop_nam.c_str(), ref.c_str());
printout(s_debug.materials ? ALWAYS : DEBUG, "Compact",
"++ material %-16s add property: %s -> %s.",
mat->GetName(), prop_nam.c_str(), ref.c_str());
continue;
}
// ERROR
throw_print("Compact2Objects[ERROR]: Converting material:" + mname + " Property missing: " + ref);
}
}
#endif
}
TGeoMedium* medium = mgr.GetMedium(matname);
if (0 == medium) {
--unique_mat_id;
medium = new TGeoMedium(matname, unique_mat_id, mat);
medium->SetTitle("material");
medium->SetUniqueID(unique_mat_id);
}
// TGeo has no notion of a material "formula"
// Hence, treat the formula the same way as the material itself
if (x_mat.hasAttr(_U(formula))) {
string form = x_mat.attr<string>(_U(formula));
if (form != matname) {
medium = mgr.GetMedium(form.c_str());
if (0 == medium) {
--unique_mat_id;
medium = new TGeoMedium(form.c_str(), unique_mat_id, mat);
medium->SetTitle("material");
medium->SetUniqueID(unique_mat_id);
}
}
}
}
/** Convert compact isotope objects
*
* <isotope name="C12" Z="2" N="12"/>
* <atom unit="g/mole" value="12"/>
* </isotope>
*/
template <> void Converter<Isotope>::operator()(xml_h e) const {
xml_dim_t isotope(e);
TGeoManager& mgr = description.manager();
string nam = isotope.nameStr();
TGeoElementTable* tab = mgr.GetElementTable();
TGeoIsotope* iso = tab->FindIsotope(nam.c_str());
// Create the isotope object in the event it is not yet present from the XML data
if ( !iso ) {
xml_ref_t atom(isotope.child(_U(atom)));
int n = isotope.attr<int>(_U(N));
int z = isotope.attr<int>(_U(Z));
double value = atom.attr<double>(_U(value));
string unit = atom.attr<string>(_U(unit));
double a = value * _multiply<double>(unit,"mol/g");
iso = new TGeoIsotope(nam.c_str(), z, n, a);
printout(s_debug.isotopes ? ALWAYS : DEBUG, "Compact",
"++ Converting isotope %-16s Z:%3d N:%3d A:%8.4f [g/mol]",
iso->GetName(), iso->GetZ(), iso->GetN(), iso->GetA());
}
else {
printout(s_debug.isotopes ? WARNING : DEBUG, "Compact",
"++ Isotope %-16s Z:%3d N:%3d A:%8.4f [g/mol] ALREADY defined. [Ignore definition]",
iso->GetName(), iso->GetZ(), iso->GetN(), iso->GetA());
}
}
/** Convert compact atom objects (periodic elements)
*
* <element Z="4" formula="Be" name="Be" >
* <atom type="A" unit="g/mol" value="9.01218" />
* </element>
* or
* <element name="C">
* <fraction n="0.9893" ref="C12"/>
* <fraction n="0.0107" ref="C13"/>
* </element>
*
* Please note:
* Elements may consist of a mixture of isotopes!
*/
template <> void Converter<Atom>::operator()(xml_h e) const {
xml_ref_t elem(e);
xml_tag_t name = elem.name();
TGeoManager& mgr = description.manager();
TGeoElementTable* tab = mgr.GetElementTable();
TGeoElement* elt = tab->FindElement(name.c_str());
if ( !elt ) {
if ( elem.hasChild(_U(atom)) ) {
xml_ref_t atom(elem.child(_U(atom)));
string formula = elem.attr<string>(_U(formula));
double value = atom.attr<double>(_U(value));
string unit = atom.attr<string>(_U(unit));
int z = elem.attr<int>(_U(Z));
double a = value*_multiply<double>(unit,"mol/g");
printout(s_debug.elements ? ALWAYS : DEBUG, "Compact",
"++ Converting element %-16s [%-3s] Z:%3d A:%8.4f [g/mol]",
name.c_str(), formula.c_str(), z, a);
tab->AddElement(name.c_str(), formula.c_str(), z, a);
}
else {
int num_isotopes = 0;
string formula = elem.hasAttr(_U(formula)) ? elem.attr<string>(_U(formula)) : name.str();
for( xml_coll_t i(elem,_U(fraction)); i; ++i)
++num_isotopes;
elt = new TGeoElement(name.c_str(), formula.c_str(), num_isotopes);
tab->AddElement(elt);
for( xml_coll_t i(elem,_U(fraction)); i; ++i) {
double frac = i.attr<double>(_U(n));
string ref = i.attr<string>(_U(ref));
TGeoIsotope* iso = tab->FindIsotope(ref.c_str());
if ( !iso ) {
except("Compact","Element %s cannot be constructed. Isotope '%s' (fraction: %.3f) missing!",
name.c_str(), ref.c_str(), frac);
}
printout(s_debug.elements ? ALWAYS : DEBUG, "Compact",
"++ Converting element %-16s Add isotope: %-16s fraction:%.4f.",
name.c_str(), ref.c_str(), frac);
elt->AddIsotope(iso, frac);
}
printout(s_debug.elements ? ALWAYS : DEBUG, "Compact",
"++ Converted element %-16s [%-3s] Z:%3d A:%8.4f [g/mol] with %d isotopes.",
name.c_str(), formula.c_str(), elt->Z(), elt->A(), num_isotopes);
}
elt = tab->FindElement(name.c_str());
if (!elt) {
throw_print("Failed to properly insert the Element:"+name+" into the element table!");
}
}
else {
printout(s_debug.elements ? WARNING : DEBUG, "Compact",
"++ Element %-16s Z:%3d N:%3d A:%8.4f [g/mol] ALREADY defined. [Ignore definition]",
elt->GetName(), elt->Z(), elt->N(), elt->A());
}
}
/** Convert compact isotope objects
*
* <std_conditions type="STP or NTP"> // type optional
* <item name="temperature" unit="kelvin" value="273.15"/>
* <item name="pressure" unit="kPa" value="100"/>
* </std_conditions>
*/
template <> void Converter<STD_Conditions>::operator()(xml_h e) const {
xml_dim_t cond(e);
// Create the isotope object in the event it is not yet present from the XML data
if ( cond.ptr() ) {
if ( cond.hasAttr(_U(type)) ) {
description.setStdConditions(cond.typeStr());
}
xml_h temperature = cond.child(_U(T), false);
double temp_val = description.stdConditions().temperature;
if ( temperature.ptr() ) {
double temp_unit = _toDouble("kelvin");
if ( temperature.hasAttr(_U(unit)) )
temp_unit = temperature.attr<double>(_U(unit));
temp_val = temperature.attr<double>(_U(value)) * temp_unit;
}
xml_h pressure = cond.child(_U(P), false);
double pressure_val = description.stdConditions().pressure;
if ( pressure.ptr() ) {
double pressure_unit = _toDouble("pascal");
if ( pressure.hasAttr(_U(unit)) )
pressure_unit = pressure.attr<double>(_U(unit));
pressure_val = pressure.attr<double>(_U(value)) * pressure_unit;
}
description.setStdConditions(temp_val, pressure_val);
printout(s_debug.materials ? ALWAYS : DEBUG, "Compact",
"+++ Material standard conditions: Temperature: %.3f Kelvin Pressure: %.3f hPa",
temp_val/_toDouble("kelvin"), pressure_val/_toDouble("hPa"));
}
}
#if ROOT_VERSION_CODE >= ROOT_VERSION(6,17,0)
/** Convert compact optical surface objects (defines)
*
*
*/
template <> void Converter<OpticalSurface>::operator()(xml_h element) const {
xml_elt_t e = element;
// Defaults from Geant4
OpticalSurface::EModel model = OpticalSurface::Model::kMglisur;
OpticalSurface::EFinish finish = OpticalSurface::Finish::kFpolished;
OpticalSurface::EType type = OpticalSurface::Type::kTdielectric_metal;
Double_t value = 1.0;
if ( e.hasAttr(_U(type)) ) type = OpticalSurface::stringToType(e.attr<string>(_U(type)));
if ( e.hasAttr(_U(model)) ) model = OpticalSurface::stringToModel(e.attr<string>(_U(model)));
if ( e.hasAttr(_U(finish)) ) finish = OpticalSurface::stringToFinish(e.attr<string>(_U(finish)));
if ( e.hasAttr(_U(value)) ) value = e.attr<double>(_U(value));
OpticalSurface surf(description, e.attr<string>(_U(name)), model, finish, type, value);
if ( s_debug.surface ) {
printout(ALWAYS,"Compact","+++ Reading optical surface %s Typ:%d model:%d finish:%d value: %.3f",
e.attr<string>(_U(name)).c_str(), int(type), int(model), int(finish), value);
}
for (xml_coll_t props(e, _U(property)); props; ++props) {
if ( props.hasAttr(_U(ref)) ) {
surf->AddProperty(props.attr<string>(_U(name)).c_str(), props.attr<string>(_U(ref)).c_str());
if ( s_debug.surface ) {
printout(ALWAYS,"Compact","+++ \t\t Property: %s -> %s",
props.attr<string>(_U(name)).c_str(), props.attr<string>(_U(ref)).c_str());
}
continue;
}
size_t cols = props.attr<long>(_U(coldim));
string nam = props.attr<string>(_U(name));
xml_attr_t opt = props.attr_nothrow(_U(option));
stringstream str(props.attr<string>(_U(values))), str_nam;
string val;
vector<double> values;
while ( !str.eof() ) {
val = "";
str >> val;
if ( val.empty() && !str.good() ) break;
values.emplace_back(_toDouble(val));
}
/// Create table and register table
TGDMLMatrix* table = new TGDMLMatrix("",values.size()/cols, cols);
if ( opt ) {
string tit = e.attr<string>(opt);
str_nam << tit << "|";
}
str_nam << nam << "__" << (void*)table;
table->SetName(str_nam.str().c_str());
table->SetTitle(nam.c_str());
for (size_t i=0, n=values.size(); i<n; ++i)
table->Set(i/cols, i%cols, values[i]);
surf->AddProperty(nam.c_str(), table->GetName());
description.manager().AddGDMLMatrix(table);
}
}
/** Convert compact constant property (Material properties stored in TGeoManager)
*
* <constant name="RINDEX" value="8.123"/>
*
*/
template <> void Converter<PropertyConstant>::operator()(xml_h e) const {
double value = e.attr<double>(_U(value));
string name = e.attr<string>(_U(name));
description.manager().AddProperty(name.c_str(), value);
if ( s_debug.matrix ) {
printout(ALWAYS,"Compact","+++ Reading property %s : %f",name.c_str(), value);
}
#if 0
xml_attr_t opt = e.attr_nothrow(_U(title));
if ( opt ) {
string val = e.attr<string>(opt);
TNamed* nam = description.manager().GetProperty(name.c_str());
if ( !nam ) {
except("Compact","Failed to access just added manager property: %s",name.c_str());
}
nam->SetTitle(val.c_str());
}
#endif
}
/** Convert compact property table objects (defines)
*
* <matrix coldim="2" name="RINDEX0xf5972d0" values="1.5e-06 1.0013 1. ...."/>
*
*/
template <> void Converter<PropertyTable>::operator()(xml_h e) const {
vector<double> vals;
size_t cols = e.attr<unsigned long>(_U(coldim));
stringstream str(e.attr<string>(_U(values)));
if ( s_debug.matrix ) {
printout(ALWAYS,"Compact","+++ Reading property table %s with %d columns.",
e.attr<string>(_U(name)).c_str(), cols);
}
vals.reserve(1024);
while ( !str.eof() ) {
string item;
str >> item;
if ( item.empty() && !str.good() ) break;
vals.emplace_back(_toDouble(item));
if ( s_debug.matrix ) {
cout << " state:" << (str.good() ? "OK " : "BAD") << " '" << item << "'";
if ( 0 == (vals.size()%cols) ) cout << endl;
}
}
if ( s_debug.matrix ) {
cout << endl;
}
/// Create table and register table
xml_attr_t opt = e.attr_nothrow(_U(option));
PropertyTable tab(description,
e.attr<string>(_U(name)),
opt ? e.attr<string>(opt).c_str() : "",
vals.size()/cols, cols);
for( size_t i=0, n=vals.size(); i < n; ++i )
tab->Set(i/cols, i%cols, vals[i]);
//if ( s_debug.matrix ) tab->Print();
}
#endif
/** Convert compact visualization attribute to Detector visualization attribute.
*
* <vis name="SiVertexBarrelModuleVis"
* alpha="1.0" r="1.0" g="0.75" b="0.76"
* drawingStyle="wireframe"
* showDaughters="false"
* visible="true"/>
*
* Optionally inherit an already defined VisAttr and override other properties.
*
* <vis name="SiVertexEndcapModuleVis"
* ref="SiVertexBarrelModuleVis"
* alpha="0.5"/>
*/
template <> void Converter<VisAttr>::operator()(xml_h e) const {
VisAttr attr(e.attr<string>(_U(name)));
float alpha = 1.0;
float red = 1.0;
float green = 1.0;
float blue = 1.0;
bool use_ref = false;
if(e.hasAttr(_U(ref))) {
use_ref = true;
auto refName = e.attr<string>(_U(ref));
const auto refAttr = description.visAttributes(refName);
if(!refAttr.isValid() ) {
throw runtime_error("reference VisAttr " + refName + " does not exist");
}
// Just copying things manually.
// I think a handle's copy constructor/assignment would reuse the underlying pointer... maybe?
refAttr.argb(alpha,red,green,blue);
attr.setColor(alpha,red,green,blue);
attr.setDrawingStyle( refAttr.drawingStyle());
attr.setLineStyle( refAttr.lineStyle());
attr.setShowDaughters(refAttr.showDaughters());
attr.setVisible(refAttr.visible());
}
xml_dim_t dim(e);
alpha = dim.alpha(alpha);
red = dim.r(red );
green = dim.g(green);
blue = dim.b(blue );
printout(s_debug.visattr ? ALWAYS : DEBUG, "Compact",
"++ Converting VisAttr structure: %-16s. Alpha=%.2f R=%.3f G=%.3f B=%.3f",
attr.name(), alpha, red, green, blue);
attr.setColor(alpha, red, green, blue);
if (e.hasAttr(_U(visible)))
attr.setVisible(e.attr<bool>(_U(visible)));
if (e.hasAttr(_U(lineStyle))) {
string ls = e.attr<string>(_U(lineStyle));
if (ls == "unbroken")
attr.setLineStyle(VisAttr::SOLID);
else if (ls == "broken")
attr.setLineStyle(VisAttr::DASHED);
}
else {
if (!use_ref)
attr.setLineStyle(VisAttr::SOLID);
}
if (e.hasAttr(_U(drawingStyle))) {
string ds = e.attr<string>(_U(drawingStyle));
if (ds == "wireframe")
attr.setDrawingStyle(VisAttr::WIREFRAME);
else if (ds == "solid")
attr.setDrawingStyle(VisAttr::SOLID);
}
else {
if (!use_ref)
attr.setDrawingStyle(VisAttr::SOLID);
}
if (e.hasAttr(_U(showDaughters)))
attr.setShowDaughters(e.attr<bool>(_U(showDaughters)));
else {
if (!use_ref)
attr.setShowDaughters(true);
}
description.addVisAttribute(attr);
}
/** Specialized converter for compact region objects.
*
*/
template <> void Converter<Region>::operator()(xml_h elt) const {
xml_dim_t e = elt;
Region region(e.nameStr());
vector<string>& limits = region.limits();
xml_attr_t cut = elt.attr_nothrow(_U(cut));
xml_attr_t threshold = elt.attr_nothrow(_U(threshold));
xml_attr_t store_secondaries = elt.attr_nothrow(_U(store_secondaries));
double ene = e.eunit(1.0), len = e.lunit(1.0);
printout(s_debug.regions ? ALWAYS : DEBUG, "Compact",
"++ Converting region structure: %s.",region.name());
if ( cut ) {
region.setCut(elt.attr<double>(cut)*len);
}
if ( threshold ) {
region.setThreshold(elt.attr<double>(threshold)*ene);
}
if ( store_secondaries ) {
region.setStoreSecondaries(elt.attr<bool>(store_secondaries));
}
for (xml_coll_t user_limits(e, _U(limitsetref)); user_limits; ++user_limits)
limits.emplace_back(user_limits.attr<string>(_U(name)));
description.addRegion(region);
}
/** Specialized converter for compact readout objects.
*
* <readout name="HcalBarrelHits">
* <segmentation type="RegularNgonCartesianGridXY" gridSizeX="3.0*cm" gridSizeY="3.0*cm" />
* <id>system:6,barrel:3,module:4,layer:8,slice:5,x:32:-16,y:-16</id>
* </readout>
*/
template <> void Converter<Segmentation>::operator()(xml_h seg) const {
string type = seg.attr<string>(_U(type));
string name = seg.hasAttr(_U(name)) ? seg.attr<string>(_U(name)) : string();
std::pair<Segmentation,IDDescriptor>* opt = _option<pair<Segmentation,IDDescriptor> >();
const BitFieldCoder* bitfield = &opt->second->decoder;
Segmentation segment(type, name, bitfield);
if ( segment.isValid() ) {
const DDSegmentation::Parameters& pars = segment.parameters();
printout(s_debug.segmentation ? ALWAYS : DEBUG, "Compact",
"++ Converting segmentation structure: %s of type %s.",name.c_str(),type.c_str());
for(const auto p : pars ) {
xml::Strng_t pNam(p->name());
if ( seg.hasAttr(pNam) ) {
string pType = p->type();
if ( pType.compare("int") == 0 ) {
typedef DDSegmentation::TypedSegmentationParameter<int> ParInt;
static_cast<ParInt*>(p)->setTypedValue(seg.attr<int>(pNam));
} else if ( pType.compare("float") == 0 ) {
typedef DDSegmentation::TypedSegmentationParameter<float> ParFloat;
static_cast<ParFloat*>(p)->setTypedValue(seg.attr<float>(pNam));
} else if ( pType.compare("doublevec") == 0 ) {
vector<double> valueVector;
string par = seg.attr<string>(pNam);
printout(s_debug.segmentation ? ALWAYS : DEBUG, "Compact",
"++ Converting this string structure: %s.",par.c_str());
vector<string> elts = DDSegmentation::splitString(par);
for (const string& spar : elts ) {
if ( spar.empty() ) continue;
valueVector.emplace_back(_toDouble(spar));
}
typedef DDSegmentation::TypedSegmentationParameter< vector<double> > ParDouVec;
static_cast<ParDouVec*>(p)->setTypedValue(valueVector);
} else if ( pType.compare("double" ) == 0) {
typedef DDSegmentation::TypedSegmentationParameter<double>ParDouble;
static_cast<ParDouble*>(p)->setTypedValue(seg.attr<double>(pNam));
} else {
p->setValue(seg.attr<string>(pNam));
}
} else if (not p->isOptional()) {
throw_print("FAILED to create segmentation: " + type +
". Missing mandatory parameter: " + p->name() + "!");
}
}
long key_min = 0, key_max = 0;
DDSegmentation::Segmentation* base = segment->segmentation;
for(xml_coll_t sub(seg,_U(segmentation)); sub; ++sub) {
std::pair<Segmentation,IDDescriptor> sub_object(Segmentation(),opt->second);
Converter<Segmentation> sub_conv(description,param,&sub_object);
sub_conv(sub);