-
Notifications
You must be signed in to change notification settings - Fork 496
Expand file tree
/
Copy pathGeneratorPythia8.cxx
More file actions
1077 lines (939 loc) · 37.6 KB
/
GeneratorPythia8.cxx
File metadata and controls
1077 lines (939 loc) · 37.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
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
// 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.
/// \author R+Preghenella - January 2020
#include "Generators/GeneratorPythia8.h"
#include "Generators/GeneratorPythia8Param.h"
#include "CommonUtils/ConfigurationMacroHelper.h"
#include <fairlogger/Logger.h>
#include "TParticle.h"
#include "TF1.h"
#include "TRandom.h"
#include "SimulationDataFormat/MCEventHeader.h"
#include "SimulationDataFormat/MCGenProperties.h"
#include "SimulationDataFormat/ParticleStatus.h"
#if PYTHIA_VERSION_INTEGER >= 8310
#include "Pythia8/HIInfo.h"
#else
#include "Pythia8/HIUserHooks.h"
#endif
#include "Pythia8Plugins/PowhegHooks.h"
#include "TSystem.h"
#include "ZDCBase/FragmentParam.h"
#include <CommonUtils/ConfigurationMacroHelper.h>
#include <filesystem>
#include <CommonUtils/FileSystemUtils.h>
#include <iostream>
#include <unordered_map>
#include <numeric>
namespace o2
{
namespace eventgen
{
std::atomic<int> GeneratorPythia8::Pythia8InstanceCounter;
/*****************************************************************/
/*****************************************************************/
// the default construct uses the GeneratorPythia8Param singleton to extract a config and delegates
// to the proper constructor
GeneratorPythia8::GeneratorPythia8() : GeneratorPythia8(GeneratorPythia8Param::Instance().detach())
{
LOG(info) << "GeneratorPythia8 constructed from GeneratorPythia8Param ConfigurableParam";
}
/*****************************************************************/
GeneratorPythia8::GeneratorPythia8(Pythia8GenConfig const& config) : Generator("ALICEo2", "ALICEo2 Pythia8 Generator")
{
/** constructor **/
mThisPythia8InstanceID = GeneratorPythia8::Pythia8InstanceCounter;
GeneratorPythia8::Pythia8InstanceCounter++;
mInterface = reinterpret_cast<void*>(&mPythia);
mInterfaceName = "pythia8";
LOG(info) << "Instance \'Pythia8\' generator with following parameters";
LOG(info) << "config: " << config.config;
LOG(info) << "hooksFileName: " << config.hooksFileName;
LOG(info) << "hooksFuncName: " << config.hooksFuncName;
mGenConfig = config;
setConfig(mGenConfig.config);
setHooksFileName(mGenConfig.hooksFileName);
setHooksFuncName(mGenConfig.hooksFuncName);
}
/*****************************************************************/
GeneratorPythia8::GeneratorPythia8(const Char_t* name, const Char_t* title) : Generator(name, title)
{
/** constructor **/
mInterface = reinterpret_cast<void*>(&mPythia);
mInterfaceName = "pythia8";
}
bool GeneratorPythia8::setInitialSeed(long seed)
{
// check first of all if Init not yet called and seed not <0
if (mIsInitialized) {
return false;
}
if (seed < 0) {
return false;
}
// sets the initial seed and applies the correct Pythia
// range
mInitialRNGSeed = seed % (MAX_SEED + 1);
LOG(info) << "GeneratorPythia8: Setting initial seed to " << mInitialRNGSeed;
return true;
}
/*****************************************************************/
void GeneratorPythia8::seedGenerator()
{
/// Function is seeding the Pythia random numbers.
/// In case a completely different logic is required by users,
/// we could make this function virtual or allow to set/execute
/// a user-given lambda function instead.
/// Note that this function is executed **before** the Pythia8
/// user config file is read. So the config file should either not contain seeding information ... or can be used to override seeding logic.
auto seed = mInitialRNGSeed;
if (seed == -1) {
// Will use the mInitialRNGSeed if it was set.
// Otherwise will seed the generator with the state of
// TRandom::GetSeed. This is the seed that is influenced from
// SimConfig --seed command line options options.
seed = gRandom->TRandom::GetSeed(); // this uses the "original" seed
// we advance the seed by one so that the next Pythia8 generator gets a different value
if (mThisPythia8InstanceID > 0) {
gRandom->Rndm();
LOG(info) << "Multiple Pythia8 generator instances detected .. automatically adjusting seed further to avoid overlap ";
seed = seed ^ gRandom->GetSeed(); // this uses the "current" seed
}
// apply max seed cuttof
seed = seed % (MAX_SEED + 1);
LOG(info) << "GeneratorPythia8: Using random seed from gRandom % 900000001: " << seed;
}
mPythia.readString("Random:setSeed on");
mPythia.readString("Random:seed " + std::to_string(seed));
}
/*****************************************************************/
Bool_t GeneratorPythia8::Init()
{
/** init **/
/** init base class **/
Generator::Init();
/** Seed the Pythia random number state.
The user may override this seeding by providing separate
Random:setSeed configurations in the configuration file.
**/
seedGenerator();
/** read configuration **/
if (!mConfig.empty()) {
std::stringstream ss(mConfig);
std::string config;
while (getline(ss, config, ' ')) {
config = gSystem->ExpandPathName(config.c_str());
LOG(info) << "Reading configuration from file: " << config;
if (!mPythia.readFile(config, true)) {
LOG(fatal) << "Failed to init \'Pythia8\': problems with configuration file "
<< config;
return false;
}
}
}
/** user hooks via configuration macro **/
if (!mHooksFileName.empty()) {
LOG(info) << "Applying \'Pythia8\' user hooks: " << mHooksFileName << " -> " << mHooksFuncName;
auto hooks = o2::conf::GetFromMacro<Pythia8::UserHooks*>(mHooksFileName, mHooksFuncName, "Pythia8::UserHooks*", "pythia8_user_hooks");
if (!hooks) {
LOG(fatal) << "Failed to init \'Pythia8\': problem with user hooks configuration ";
return false;
}
setUserHooks(hooks);
}
#if PYTHIA_VERSION_INTEGER < 8300
/** [NOTE] The issue with large particle production vertex when running
Pythia8 heavy-ion model (Angantyr) is solved in Pythia 8.3 series.
For discussions about this issue, please refer to this JIRA ticket
https://alice.its.cern.ch/jira/browse/O2-1382.
The code remains within preprocessor directives, both for reference
and in case future use demands to roll back to Pythia 8.2 series. **/
/** inhibit hadron decays **/
mPythia.readString("HadronLevel:Decay off");
#endif
if (mPythia.settings.mode("Beams:frameType") == 4) {
// Hook for POWHEG
// Read in key POWHEG merging settings
int vetoMode = mPythia.settings.mode("POWHEG:veto");
int MPIvetoMode = mPythia.settings.mode("POWHEG:MPIveto");
bool loadHooks = (vetoMode > 0 || MPIvetoMode > 0);
// Add in user hooks for shower vetoing
std::shared_ptr<Pythia8::PowhegHooks> powhegHooks;
if (loadHooks) {
// Set ISR and FSR to start at the kinematical limit
if (vetoMode > 0) {
mPythia.readString("SpaceShower:pTmaxMatch = 2");
mPythia.readString("TimeShower:pTmaxMatch = 2");
}
// Set MPI to start at the kinematical limit
if (MPIvetoMode > 0) {
mPythia.readString("MultipartonInteractions:pTmaxMatch = 2");
}
powhegHooks = std::make_shared<Pythia8::PowhegHooks>();
mPythia.setUserHooksPtr((Pythia8::UserHooksPtr)powhegHooks);
}
}
/** Add 20Neon to collision particle database */
mPythia.particleData.addParticle(1000100200, "20Ne", 6, 30, 0, 19.992440);
/** initialise **/
if (!mPythia.init()) {
LOG(fatal) << "Failed to init \'Pythia8\': init returned with error";
return false;
}
initUserFilterCallback();
mIsInitialized = true;
/** success **/
return true;
}
/*****************************************************************/
void GeneratorPythia8::setUserHooks(Pythia8::UserHooks* hooks)
{
#if PYTHIA_VERSION_INTEGER < 8300
mPythia.setUserHooksPtr(hooks);
#else
mPythia.setUserHooksPtr(std::shared_ptr<Pythia8::UserHooks>(hooks));
#endif
}
/*****************************************************************/
Bool_t
GeneratorPythia8::generateEvent()
{
/** generate event **/
if (!mPythia.next()) {
return false;
}
#if PYTHIA_VERSION_INTEGER < 8300
/** [NOTE] The issue with large particle production vertex when running
Pythia8 heavy-ion model (Angantyr) is solved in Pythia 8.3 series.
For discussions about this issue, please refer to this JIRA ticket
https://alice.its.cern.ch/jira/browse/O2-1382.
The code remains within preprocessor directives, both for reference
and in case future use demands to roll back to Pythia 8.2 series. **/
/** As we have inhibited all hadron decays before init,
the event generation stops after hadronisation.
We then pick all particles from here and force their
production vertex to be (0,0,0,0).
Afterwards we process the decays. **/
/** force production vertices to (0,0,0,0) **/
auto nParticles = mPythia.event.size();
for (int iparticle = 0; iparticle < nParticles; iparticle++) {
auto& aParticle = mPythia.event[iparticle];
aParticle.xProd(0.);
aParticle.yProd(0.);
aParticle.zProd(0.);
aParticle.tProd(0.);
}
/** proceed with decays **/
if (!mPythia.moreDecays())
return false;
#endif
/** success **/
return true;
}
/*****************************************************************/
void GeneratorPythia8::investigateRelatives(Pythia8::Event& event,
const std::vector<int>& old2New,
size_t index,
std::vector<bool>& done,
GetRelatives getter,
SetRelatives setter,
FirstLastRelative firstLast,
const std::string& what,
const std::string& ind)
{
// Utility to find new index, or -1 if not found
auto findNew = [old2New](size_t old) -> int {
return old2New[old];
};
int newIdx = findNew(index);
int hepmc = event[index].statusHepMC();
LOG(debug) << ind
<< index << " -> "
<< newIdx << " (" << hepmc << ") ";
if (done[index]) {
LOG(debug) << ind << " already done";
return;
}
// Our list of new relatives
using IdList = std::pair<int, int>;
constexpr int invalid = 0xFFFFFFF;
IdList newRelatives = std::make_pair(invalid, -invalid);
// Utility to add id
auto addId = [](IdList& l, size_t id) {
l.first = std::min(int(id), l.first);
l.second = std::max(int(id), l.second);
};
// Get particle and relatives
auto& particle = event[index];
auto relatives = getter(particle);
LOG(debug) << ind << " Check " << what << "s ["
<< std::setw(3) << firstLast(particle).first << ","
<< std::setw(3) << firstLast(particle).second << "] "
<< relatives.size();
for (auto relativeIdx : relatives) {
int newRelative = findNew(relativeIdx);
if (newRelative >= 0) {
// If this relative is to be kept, then append to list of new
// relatives.
LOG(debug) << ind << " "
<< what << " "
<< relativeIdx << " -> "
<< newRelative << " to be kept" << std::endl;
addId(newRelatives, newRelative);
continue;
}
LOG(debug) << ind << " "
<< what << " "
<< relativeIdx << " not to be kept "
<< (done[relativeIdx] ? "already done" : "to be done")
<< std::endl;
// Below is code for when the relative is not to be kept
auto& relative = event[relativeIdx];
if (not done[relativeIdx]) {
// IF the relative hasn't been processed yet, do so now
investigateRelatives(event, // Event
old2New, // Map from old to new
relativeIdx, // current particle index
done, // cache flag
getter, // get mother relatives
setter, // set mother relatives
firstLast, // get first and last
what, // what we're looking at
ind + " "); // Logging indent
}
// If this relative was already done, then get its relatives and
// add them to the list of new relatives.
auto grandRelatives = firstLast(relative);
int grandRelative1 = grandRelatives.first;
int grandRelative2 = grandRelatives.second;
assert(grandRelative1 != invalid);
assert(grandRelative2 != -invalid);
if (grandRelative1 > 0) {
addId(newRelatives, grandRelative1);
}
if (grandRelative2 > 0) {
addId(newRelatives, grandRelative2);
}
LOG(debug) << ind << " "
<< what << " "
<< relativeIdx << " gave new relatives "
<< grandRelative1 << " -> " << grandRelative2;
}
LOG(debug) << ind << " Got "
<< (newRelatives.second - newRelatives.first + 1) << " new "
<< what << "s ";
if (newRelatives.first != invalid) {
// If the first relative is not invalid, then the second isn't
// either (possibly the same though).
int newRelative1 = newRelatives.first;
int newRelative2 = newRelatives.second;
setter(particle, newRelative1, newRelative2);
LOG(debug) << ind << " " << what << "s: "
<< firstLast(particle).first << " ("
<< newRelative1 << "),"
<< firstLast(particle).second << " ("
<< newRelative2 << ")";
} else {
setter(particle, 0, 0);
}
done[index] = true;
}
/*****************************************************************/
void GeneratorPythia8::pruneEvent(Pythia8::Event& event, Select select)
{
// Mapping from old to new index.
std::vector<int> old2new(event.size(), -1);
// Particle 0 is a system particle, and we will skip that in the
// following.
size_t newId = 0;
// Loop over particles and store those we need
for (size_t i = 1; i < event.size(); i++) {
auto& particle = event[i];
if (select(particle)) {
++newId;
old2new[i] = newId;
}
}
// Utility to find new index, or -1 if not found
auto findNew = [old2new](size_t old) -> int {
return old2new[old];
};
// First loop, investigate mothers - from the bottom
auto getMothers = [](const Pythia8::Particle& particle) { return particle.motherList(); };
auto setMothers = [](Pythia8::Particle& particle, int m1, int m2) { particle.mothers(m1, m2); };
auto firstLastMothers = [](const Pythia8::Particle& particle) { return std::make_pair(particle.mother1(), particle.mother2()); };
std::vector<bool> motherDone(event.size(), false);
for (size_t i = 1; i < event.size(); ++i) {
investigateRelatives(event, // Event
old2new, // Map from old to new
i, // current particle index
motherDone, // cache flag
getMothers, // get mother relatives
setMothers, // set mother relatives
firstLastMothers, // get first and last
"mother"); // what we're looking at
}
// Second loop, investigate daughters - from the top
auto getDaughters = [](const Pythia8::Particle& particle) {
// In case of |status|==13 (diffractive), we cannot use
// Pythia8::Particle::daughterList as it will give more than
// just the immediate daughters. In that cae, we do it
// ourselves.
if (std::abs(particle.status()) == 13) {
int d1 = particle.daughter1();
int d2 = particle.daughter2();
if (d1 == 0 and d2 == 0) {
return std::vector<int>();
}
if (d2 == 0) {
return std::vector<int>{d1};
}
if (d2 > d1) {
std::vector<int> ret(d2-d1+1);
std::iota(ret.begin(), ret.end(), d1);
return ret;
}
return std::vector<int>{d2,d1};
}
return particle.daughterList(); };
auto setDaughters = [](Pythia8::Particle& particle, int d1, int d2) { particle.daughters(d1, d2); };
auto firstLastDaughters = [](const Pythia8::Particle& particle) { return std::make_pair(particle.daughter1(), particle.daughter2()); };
std::vector<bool> daughterDone(event.size(), false);
for (size_t i = event.size() - 1; i > 0; --i) {
investigateRelatives(event, // Event
old2new, // Map from old to new
i, // current particle index
daughterDone, // cache flag
getDaughters, // get mother relatives
setDaughters, // set mother relatives
firstLastDaughters, // get first and last
"daughter"); // what we're looking at
}
// Make a pruned event
Pythia8::Event pruned;
pruned.init("Pruned event", &mPythia.particleData);
pruned.reset();
for (size_t i = 1; i < event.size(); i++) {
int newIdx = findNew(i);
if (newIdx < 0) {
continue;
}
auto particle = event[i];
int realIdx = pruned.append(particle);
assert(realIdx == newIdx);
}
// We may have that two or more mothers share some daughters, but
// that one or more mothers have more daughters than the other
// mothers, and hence not all daughters point back to all mothers.
// This can happen, for example, if a beam particle radiates
// on-shell particles before an interaction with any daughters
// from the other mothers. Thus, we need to take care of that or
// the event record will be corrupted.
//
// What we do is that for all particles, we look up the daughters.
// Then for each daughter, we check the mothers of those
// daughters. If this list of mothers include other mothers than
// the currently investigated mother, we must change the mothers
// of the currently investigated daughters.
using IdList = std::pair<int, int>;
// Utility to add id
auto addId = [](IdList& l, size_t id) {
l.first = std::min(int(id), l.first);
l.second = std::max(int(id), l.second);
};
constexpr int invalid = 0xFFFFFFF;
std::vector<bool> shareDone(pruned.size(), false);
for (size_t i = 1; i < pruned.size(); i++) {
if (shareDone[i]) {
continue;
}
auto& particle = pruned[i];
auto daughters = particle.daughterList();
IdList allDaughters = std::make_pair(invalid, -invalid);
IdList allMothers = std::make_pair(invalid, -invalid);
addId(allMothers, i);
for (auto daughterIdx : daughters) {
// Add this daughter to set of all daughters
addId(allDaughters, daughterIdx);
auto& daughter = pruned[daughterIdx];
auto otherMothers = daughter.motherList();
for (auto otherMotherIdx : otherMothers) {
// Add this mother to set of all mothers. That is, take all
// mothers of the current daughter of the current particle
// and store that. In this way, we register mothers that
// share a daughter with the current particle.
addId(allMothers, otherMotherIdx);
// We also need to take all the daughters of this shared
// mother and reister those.
auto& otherMother = pruned[otherMotherIdx];
int otherDaughter1 = otherMother.daughter1();
int otherDaughter2 = otherMother.daughter2();
if (otherDaughter1 > 0) {
addId(allDaughters, otherDaughter1);
}
if (otherDaughter2 > 0) {
addId(allDaughters, otherDaughter2);
}
}
// At this point, we have added all mothers of current
// daughter, and all daughters of those mothers.
}
// At this point, we have all mothers that share daughters with
// the current particle, and we have all of the daughters
// too.
//
// We can now update the daughter information on all mothers
int minDaughter = allDaughters.first;
int maxDaughter = allDaughters.second;
int minMother = allMothers.first;
int maxMother = allMothers.second;
if (minMother != invalid) {
// If first mother isn't invalid, then second isn't either
for (size_t motherIdx = minMother; motherIdx <= maxMother; //
motherIdx++) {
shareDone[motherIdx] = true;
if (minDaughter == invalid) {
pruned[motherIdx].daughters(0, 0);
} else {
pruned[motherIdx].daughters(minDaughter, maxDaughter);
}
}
}
if (minDaughter != invalid) {
// If least mother isn't invalid, then largest mother will not
// be invalid either.
for (size_t daughterIdx = minDaughter; daughterIdx <= maxDaughter; //
daughterIdx++) {
if (minMother == invalid) {
pruned[daughterIdx].mothers(0, 0);
} else {
pruned[daughterIdx].mothers(minMother, maxMother);
}
}
}
}
if (mGenConfig.verbose) {
LOG(info) << "Pythia event was pruned from " << event.size()
<< " to " << pruned.size() << " particles";
}
// Assign our pruned event to the event passed in
event = pruned;
}
/*****************************************************************/
void GeneratorPythia8::initUserFilterCallback()
{
mUserFilterFcn = [](Pythia8::Particle const&) -> bool { return true; };
std::string filter = mGenConfig.particleFilter;
if (filter.size() > 0) {
LOG(info) << "Initializing the callback for user-based particle pruning " << filter;
auto expandedFileName = o2::utils::expandShellVarsInFileName(filter);
if (std::filesystem::exists(expandedFileName)) {
// if the filter is in a file we will compile the hook on the fly
mUserFilterFcn = o2::conf::GetFromMacro<UserFilterFcn>(expandedFileName, "filterPythia()", "o2::eventgen::GeneratorPythia8::UserFilterFcn", "o2mc_pythia8_userfilter_hook");
LOG(info) << "Hook initialized from file " << expandedFileName;
} else {
// if it's not a file we interpret it as a C++ lambda string and JIT it directly;
LOG(error) << "Did not find a file " << expandedFileName << " ; Will not execute hook";
}
mApplyPruning = true;
}
}
/*****************************************************************/
Bool_t
GeneratorPythia8::importParticles(Pythia8::Event& event)
{
/** import particles **/
// The right moment to filter out unwanted stuff (like parton-level
// event information) Here, we aim to filter out everything before
// hadronization with the motivation to reduce the size of the MC
// event record in the AOD.
std::function<bool(const Pythia8::Particle&)> partonSelect = [](const Pythia8::Particle&) { return true; };
bool includeParton = mGenConfig.includePartonEvent;
if (not includeParton) {
// Select pythia particles
partonSelect = [](const Pythia8::Particle& particle) {
switch (particle.statusHepMC()) {
case 1: // Final st
case 2: // Decayed
case 4: // Beam
return true;
}
// For example to keep diffractive particles
// if (particle.id() == 9902210) return true;
return false;
};
mApplyPruning = true;
}
if (mApplyPruning) {
auto finalSelect = [partonSelect, this](const Pythia8::Particle& p) { return partonSelect(p) && mUserFilterFcn(p); };
pruneEvent(event, finalSelect);
}
/* loop over particles */
auto nParticles = event.size();
for (Int_t iparticle = 1; iparticle < nParticles; iparticle++) {
// first particle is system
auto particle = event[iparticle];
auto pdg = particle.id();
auto st = o2::mcgenstatus::MCGenStatusEncoding(particle.statusHepMC(), //
particle.status()) //
.fullEncoding;
mParticles.push_back(TParticle(pdg, // Particle type
st, // status
particle.mother1() - 1, // first mother
particle.mother2() - 1, // second mother
particle.daughter1() - 1, // first daughter
particle.daughter2() - 1, // second daughter
particle.px(), // X-momentum
particle.py(), // Y-momentum
particle.pz(), // Z-momentum
particle.e(), // Energy
particle.xProd(), // Production X
particle.yProd(), // Production Y
particle.zProd(), // Production Z
particle.tProd())); // Production t
mParticles.back().SetBit(ParticleStatus::kToBeDone, //
particle.statusHepMC() == 1);
}
/** success **/
return kTRUE;
}
/*****************************************************************/
void GeneratorPythia8::updateHeader(o2::dataformats::MCEventHeader* eventHeader)
{
/** update header **/
using Key = o2::dataformats::MCInfoKeys;
eventHeader->putInfo<std::string>(Key::generator, "pythia8");
eventHeader->putInfo<int>(Key::generatorVersion, PYTHIA_VERSION_INTEGER);
eventHeader->putInfo<std::string>(Key::processName, mPythia.info.name());
eventHeader->putInfo<int>(Key::processCode, mPythia.info.code());
eventHeader->putInfo<float>(Key::weight, mPythia.info.weight());
auto& info = mPythia.info;
eventHeader->putInfo<int>(Key::acceptedEvents, info.nAccepted());
eventHeader->putInfo<int>(Key::attemptedEvents, info.nTried());
// Set PDF information
eventHeader->putInfo<int>(Key::pdfParton1Id, info.id1pdf());
eventHeader->putInfo<int>(Key::pdfParton2Id, info.id2pdf());
eventHeader->putInfo<float>(Key::pdfX1, info.x1pdf());
eventHeader->putInfo<float>(Key::pdfX2, info.x2pdf());
eventHeader->putInfo<float>(Key::pdfScale, info.QFac());
eventHeader->putInfo<float>(Key::pdfXF1, info.pdf1());
eventHeader->putInfo<float>(Key::pdfXF2, info.pdf2());
// Set cross section
eventHeader->putInfo<float>(Key::xSection, info.sigmaGen() * 1e9);
eventHeader->putInfo<float>(Key::xSectionError, info.sigmaErr() * 1e9);
// Set event scale and nMPI
eventHeader->putInfo<float>(Key::eventScale, info.QRen());
eventHeader->putInfo<int>(Key::mpi, info.nMPI());
// Set weights (overrides cross-section for each weight)
size_t iw = 0;
auto xsecErr = info.weightContainerPtr->getTotalXsecErr();
for (auto w : info.weightContainerPtr->getTotalXsec()) {
std::string post = (iw == 0 ? "" : "_" + std::to_string(iw));
eventHeader->putInfo<float>(Key::weight + post, info.weightValueByIndex(iw));
eventHeader->putInfo<float>(Key::xSection + post, w * 1e9);
eventHeader->putInfo<float>(Key::xSectionError + post, xsecErr[iw] * 1e9);
iw++;
}
#if PYTHIA_VERSION_INTEGER < 8300
auto hiinfo = mPythia.info.hiinfo;
#else
auto hiinfo = mPythia.info.hiInfo;
#endif
if (hiinfo) {
/** set impact parameter **/
eventHeader->SetB(hiinfo->b());
eventHeader->putInfo<double>(Key::impactParameter, hiinfo->b());
/** set event plane angle **/
#if PYTHIA_VERSION_INTEGER >= 8310
eventHeader->putInfo<double>(Key::planeAngle, hiinfo->phi());
#endif
auto bImp = hiinfo->b();
/** set Ncoll, Npart and Nremn **/
int nColl, nPart;
int nPartProtonProj, nPartNeutronProj, nPartProtonTarg, nPartNeutronTarg;
int nRemnProtonProj, nRemnNeutronProj, nRemnProtonTarg, nRemnNeutronTarg;
int nFreeNeutronProj, nFreeProtonProj, nFreeNeutronTarg, nFreeProtonTarg;
getNcoll(nColl);
getNpart(nPart);
getNpart(nPartProtonProj, nPartNeutronProj, nPartProtonTarg, nPartNeutronTarg);
getNremn(nRemnProtonProj, nRemnNeutronProj, nRemnProtonTarg, nRemnNeutronTarg);
getNfreeSpec(nFreeNeutronProj, nFreeProtonProj, nFreeNeutronTarg, nFreeProtonTarg);
eventHeader->putInfo<int>(Key::nColl, nColl);
// These are all non-HepMC3 fields - of limited use
eventHeader->putInfo<int>("Npart", nPart);
eventHeader->putInfo<int>("Npart_proj_p", nPartProtonProj);
eventHeader->putInfo<int>("Npart_proj_n", nPartNeutronProj);
eventHeader->putInfo<int>("Npart_targ_p", nPartProtonTarg);
eventHeader->putInfo<int>("Npart_targ_n", nPartNeutronTarg);
eventHeader->putInfo<int>("Nremn_proj_p", nRemnProtonProj);
eventHeader->putInfo<int>("Nremn_proj_n", nRemnNeutronProj);
eventHeader->putInfo<int>("Nremn_targ_p", nRemnProtonTarg);
eventHeader->putInfo<int>("Nremn_targ_n", nRemnNeutronTarg);
eventHeader->putInfo<int>("Nfree_proj_n", nFreeNeutronProj);
eventHeader->putInfo<int>("Nfree_proj_p", nFreeProtonProj);
eventHeader->putInfo<int>("Nfree_targ_n", nFreeNeutronTarg);
eventHeader->putInfo<int>("Nfree_targ_p", nFreeProtonTarg);
// --- HepMC3 conforming information ---
// This is how the Pythia authors define Ncoll
// eventHeader->putInfo<int>(Key::nColl,
// hiinfo->nAbsProj() + hiinfo->nDiffProj() +
// hiinfo->nAbsTarg() + hiinfo->nDiffTarg() -
// hiiinfo->nCollND() - hiinfo->nCollDD());
eventHeader->putInfo<int>(Key::nPartProjectile,
hiinfo->nAbsProj() + hiinfo->nDiffProj());
eventHeader->putInfo<int>(Key::nPartTarget,
hiinfo->nAbsTarg() + hiinfo->nDiffTarg());
#if PYTHIA_VERSION_INTEGER >= 8313
eventHeader->putInfo<int>(Key::nCollHard, hiinfo->nCollND());
#else
eventHeader->putInfo<int>(Key::nCollHard, hiinfo->nCollNDTot());
#endif
}
}
/*****************************************************************/
void GeneratorPythia8::selectFromAncestor(int ancestor, Pythia8::Event& inputEvent, Pythia8::Event& outputEvent)
{
/** select from ancestor
fills the output event with all particles related to
an ancestor of the input event **/
// recursive selection via lambda function
std::set<int> selected;
std::function<void(int)> select;
select = [&](int i) {
selected.insert(i);
auto dl = inputEvent[i].daughterList();
for (auto j : dl) {
select(j);
}
};
select(ancestor);
// map selected particle index to output index
std::map<int, int> indexMap;
int index = outputEvent.size();
for (auto i : selected) {
indexMap[i] = index++;
}
// adjust mother/daughter indices and append to output event
for (auto i : selected) {
auto p = mPythia.event[i];
auto m1 = indexMap[p.mother1()];
auto m2 = indexMap[p.mother2()];
auto d1 = indexMap[p.daughter1()];
auto d2 = indexMap[p.daughter2()];
p.mothers(m1, m2);
p.daughters(d1, d2);
outputEvent.append(p);
}
}
/*****************************************************************/
void GeneratorPythia8::getNcoll(const Pythia8::Info& info, int& nColl)
{
/** compute number of collisions from sub-collision information **/
#if PYTHIA_VERSION_INTEGER < 8300
auto hiinfo = info.hiinfo;
#else
auto hiinfo = info.hiInfo;
#endif
nColl = 0;
if (!hiinfo) {
LOG(warn) << "No heavy-ion information from Pythia";
return;
}
// This is how the Pythia authors define Ncoll
nColl = (hiinfo->nAbsProj() + hiinfo->nDiffProj() +
hiinfo->nAbsTarg() + hiinfo->nDiffTarg() -
hiinfo->nCollND() - hiinfo->nCollDD());
if (not hiinfo->subCollisionsPtr()) {
#if PYTHIA_VERSION_INTEGER < 8310
LOG(fatal) << "No sub-collision pointer from Pythia";
#endif
return;
}
// loop over sub-collisions
auto scptr = hiinfo->subCollisionsPtr();
for (auto sc : *scptr) {
// wounded nucleon flag in projectile/target
auto pW = sc.proj->status() == Pythia8::Nucleon::ABS; // according to C.Bierlich this should be == Nucleon::ABS
auto tW = sc.targ->status() == Pythia8::Nucleon::ABS;
// increase number of collisions if both are wounded
if (pW && tW) {
nColl++;
}
}
}
/*****************************************************************/
void GeneratorPythia8::getNpart(const Pythia8::Info& info, int& nPart)
{
/** compute number of participants as the sum of all participants nucleons **/
#if PYTHIA_VERSION_INTEGER < 8300
auto hiinfo = info.hiinfo;
#else
auto hiinfo = info.hiInfo;
#endif
nPart = 0;
if (not hiinfo) {
return;
}
// This is how the Pythia authors calculate Npart
nPart = (hiinfo->nAbsProj() + hiinfo->nDiffProj() +
hiinfo->nAbsTarg() + hiinfo->nDiffTarg());
if (not hiinfo->subCollisionsPtr()) {
return;
}
int nProtonProj, nNeutronProj, nProtonTarg, nNeutronTarg;
getNpart(info, nProtonProj, nNeutronProj, nProtonTarg, nNeutronTarg);
nPart = nProtonProj + nNeutronProj + nProtonTarg + nNeutronTarg;
}
/*****************************************************************/
void GeneratorPythia8::getNpart(const Pythia8::Info& info, int& nProtonProj, int& nNeutronProj, int& nProtonTarg, int& nNeutronTarg)
{
/** compute number of participants from sub-collision information **/
#if PYTHIA_VERSION_INTEGER < 8300
auto hiinfo = info.hiinfo;
#else
auto hiinfo = info.hiInfo;
#endif
nProtonProj = nNeutronProj = nProtonTarg = nNeutronTarg = 0;
if (!hiinfo) {
return;
}
nProtonProj = hiinfo->nAbsProj() + hiinfo->nDiffProj();
nProtonTarg = hiinfo->nAbsTarg() + hiinfo->nDiffTarg();
if (not hiinfo->subCollisionsPtr()) {
#if PYTHIA_VERSION_INTEGER < 8310
LOG(fatal) << "No sub-collision pointer from Pythia";
#endif
return;
}
// keep track of wounded nucleons
std::vector<Pythia8::Nucleon*> projW;
std::vector<Pythia8::Nucleon*> targW;
// loop over sub-collisions
auto scptr = hiinfo->subCollisionsPtr();
for (auto sc : *scptr) {
// wounded nucleon flag in projectile/target
auto pW = sc.proj->status() == Pythia8::Nucleon::ABS || sc.proj->status() == Pythia8::Nucleon::DIFF; // according to C.Bierlich this should be == Nucleon::ABS || Nucleon::DIFF
auto tW = sc.targ->status() == Pythia8::Nucleon::ABS || sc.targ->status() == Pythia8::Nucleon::DIFF;
// increase number of wounded projectile nucleons if not yet in the wounded vector
if (pW && std::find(projW.begin(), projW.end(), sc.proj) == projW.end()) {
projW.push_back(sc.proj);
if (sc.proj->id() == 2212) {
nProtonProj++;
} else if (sc.proj->id() == 2112) {
nNeutronProj++;
}
}
// increase number of wounded target nucleons if not yet in the wounded vector
if (tW && std::find(targW.begin(), targW.end(), sc.targ) == targW.end()) {
targW.push_back(sc.targ);
if (sc.targ->id() == 2212) {
nProtonTarg++;
} else if (sc.targ->id() == 2112) {
nNeutronTarg++;
}
}
}
}
/*****************************************************************/
void GeneratorPythia8::getNremn(const Pythia8::Event& event, int& nProtonProj, int& nNeutronProj, int& nProtonTarg, int& nNeutronTarg)
{
/** compute number of spectators from the nuclear remnant of the beams **/
// reset
nProtonProj = nNeutronProj = nProtonTarg = nNeutronTarg = 0;
auto nNucRem = 0;
// particle loop
auto nparticles = event.size();
for (int ipa = 0; ipa < nparticles; ++ipa) {
const auto particle = event[ipa];
auto pdg = particle.id();
// nuclear remnants have pdg code = ±10LZZZAAA9
if (pdg < 1000000000) {
continue; // must be nucleus
}
if (pdg % 10 != 9) {
continue; // first digit must be 9
}
nNucRem++;
// extract A, Z and L from pdg code
pdg /= 10;
auto A = pdg % 1000;
pdg /= 1000;
auto Z = pdg % 1000;
pdg /= 1000;
auto L = pdg % 10;
if (particle.pz() > 0.) {
nProtonProj = Z;
nNeutronProj = A - Z;