-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventGenerator.cc
1350 lines (1177 loc) · 43.1 KB
/
EventGenerator.cc
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
// -*- C++ -*-
//
// EventGenerator.cc is a part of ThePEG - Toolkit for HEP Event Generation
// Copyright (C) 1999-2011 Leif Lonnblad
//
// ThePEG is licenced under version 2 of the GPL, see COPYING for details.
// Please respect the MCnet academic guidelines, see GUIDELINES for details.
//
//
// This is the implementation of the non-inlined, non-templated member
// functions of the EventGenerator class.
//
#include "EventGenerator.h"
#include "EventGenerator.xh"
#include "ThePEG/Handlers/EventHandler.h"
#include "Repository.h"
#include "ThePEG/Utilities/HoldFlag.h"
#include "ThePEG/Utilities/Debug.h"
#include "ThePEG/Utilities/DebugItem.h"
#include "ThePEG/Interface/Interfaced.h"
#include "ThePEG/Interface/Reference.h"
#include "ThePEG/Interface/RefVector.h"
#include "ThePEG/Interface/Parameter.h"
#include "ThePEG/Interface/Switch.h"
#include "ThePEG/Interface/Command.h"
#include "ThePEG/Interface/ClassDocumentation.h"
#include "ThePEG/PDT/ParticleData.h"
#include "ThePEG/PDT/MatcherBase.h"
#include "ThePEG/PDT/DecayMode.h"
#include "ThePEG/StandardModel/StandardModelBase.h"
#include "ThePEG/Repository/Strategy.h"
#include "ThePEG/Repository/CurrentGenerator.h"
#include "ThePEG/Handlers/AnalysisHandler.h"
#include "ThePEG/Analysis/FactoryBase.h"
#include "ThePEG/Handlers/EventManipulator.h"
#include "ThePEG/Handlers/LuminosityFunction.h"
#include "ThePEG/MatrixElement/MEBase.h"
#include "ThePEG/EventRecord/Event.h"
#include "ThePEG/Handlers/SubProcessHandler.h"
#include "ThePEG/Handlers/CascadeHandler.h"
#include "ThePEG/Handlers/HadronizationHandler.h"
#include "ThePEG/Persistency/PersistentOStream.h"
#include "ThePEG/Persistency/PersistentIStream.h"
#include "ThePEG/Config/algorithm.h"
#include "ThePEG/Utilities/DynamicLoader.h"
#include <cstdlib>
#include "ThePEG/Repository/Main.h"
#include <csignal>
#ifdef ThePEG_TEMPLATES_IN_CC_FILE
#include "EventGenerator.tcc"
#endif
using namespace ThePEG;
namespace {
volatile sig_atomic_t THEPEG_SIGNAL_STATE = 0;
}
// signal handler function
// very restricted in what it is allowed do
// without causing undefined behaviour
extern "C" {
void thepegSignalHandler(int id) {
THEPEG_SIGNAL_STATE=id;
signal(id,SIG_DFL);
}
}
void EventGenerator::checkSignalState() {
if (THEPEG_SIGNAL_STATE) {
finalize();
exit(0);
}
}
EventGenerator::EventGenerator()
: thePath("."), theNumberOfEvents(1000), theQuickSize(7000),
preinitializing(false), ieve(0), weightSum(0.0),
theDebugLevel(0), logNonDefault(-1), printEvent(0), dumpPeriod(0),
keepAllDumps(false),
debugEvent(0), maxWarnings(10), maxErrors(10), theCurrentRandom(0),
theCurrentGenerator(0), useStdout(false) {}
EventGenerator::EventGenerator(const EventGenerator & eg)
: Interfaced(eg), theDefaultObjects(eg.theDefaultObjects),
theLocalParticles(eg.theLocalParticles),
theStandardModel(eg.theStandardModel),
theStrategy(eg.theStrategy), theRandom(eg.theRandom),
theEventHandler(eg.theEventHandler),
theAnalysisHandlers(eg.theAnalysisHandlers),
theHistogramFactory(eg.theHistogramFactory),
theEventManipulator(eg.theEventManipulator),
thePath(eg.thePath), theRunName(eg.theRunName),
theNumberOfEvents(eg.theNumberOfEvents), theObjects(eg.theObjects),
theObjectMap(eg.theObjectMap),
theParticles(eg.theParticles), theQuickParticles(eg.theQuickParticles),
theQuickSize(eg.theQuickSize), preinitializing(false),
theMatchers(eg.theMatchers),
usedObjects(eg.usedObjects), ieve(eg.ieve), weightSum(eg.weightSum),
theDebugLevel(eg.theDebugLevel), logNonDefault(eg.logNonDefault),
printEvent(eg.printEvent), dumpPeriod(eg.dumpPeriod),
keepAllDumps(eg.keepAllDumps),
debugEvent(eg.debugEvent),
maxWarnings(eg.maxWarnings), maxErrors(eg.maxErrors), theCurrentRandom(0),
theCurrentGenerator(0),
theCurrentEventHandler(eg.theCurrentEventHandler),
theCurrentStepHandler(eg.theCurrentStepHandler),
useStdout(eg.useStdout) {}
EventGenerator::~EventGenerator() {
if ( theCurrentRandom ) delete theCurrentRandom;
if ( theCurrentGenerator ) delete theCurrentGenerator;
}
IBPtr EventGenerator::clone() const {
return new_ptr(*this);
}
IBPtr EventGenerator::fullclone() const {
return new_ptr(*this);
}
tcEventPtr EventGenerator::currentEvent() const {
return eventHandler()->currentEvent();
}
CrossSection EventGenerator::histogramScale() const {
return eventHandler()->histogramScale();
}
CrossSection EventGenerator::integratedXSec() const {
return eventHandler()->integratedXSec();
}
CrossSection EventGenerator::integratedXSecErr() const {
return eventHandler()->integratedXSecErr();
}
void
EventGenerator::setup(string newRunName,
ObjectSet & newObjects,
ParticleMap & newParticles,
MatcherSet & newMatchers) {
HoldFlag<int> debug(Debug::level, Debug::isset? Debug::level: theDebugLevel);
theRunName = newRunName;
theObjects.swap(newObjects);
theParticles.swap(newParticles);
theMatchers.swap(newMatchers);
theObjectMap.clear();
for ( ObjectSet::const_iterator it = objects().begin();
it != objects().end(); ++it ) theObjectMap[(**it).fullName()] = *it;
UseRandom currentRandom(theRandom);
CurrentGenerator currentGenerator(this);
// Force update of all objects and then reset.
touch();
for_each(theObjects, mem_fun(&InterfacedBase::touch));
update();
for_each(theObjects, mem_fun(&InterfacedBase::update));
clear();
BaseRepository::clearAll(theObjects);
init();
}
IBPtr EventGenerator::getPointer(string name) const {
ObjectMap::const_iterator it = objectMap().find(name);
if ( it == objectMap().end() ) return IBPtr();
else return it->second;
}
void EventGenerator::openOutputFiles() {
if ( !useStdout ) {
logfile().open((filename() + ".log").c_str());
theOutFileName = filename() + ".out";
outfile().open(theOutFileName.c_str());
outfile().close();
theOutStream.str("");
}
out() << Repository::banner() << endl;
log() << Repository::banner() << endl;
}
void EventGenerator::closeOutputFiles() {
flushOutputFile();
if ( !useStdout ) logfile().close();
}
void EventGenerator::flushOutputFile() {
if ( !useStdout ) {
outfile().open(theOutFileName.c_str(), ios::out|ios::app);
outfile() << theOutStream.str();
outfile().close();
} else
BaseRepository::cout() << theOutStream.str();
theOutStream.str("");
}
void EventGenerator::doinit() {
HoldFlag<int> debug(Debug::level, Debug::isset? Debug::level: theDebugLevel);
// First initialize base class and random number generator.
Interfaced::doinit();
random().init();
// Make random generator and this available in standard static
// classes.
UseRandom useRandom(theRandom);
CurrentGenerator currentGenerator(this);
// First initialize all objects which have requested this by
// implementing a InterfacedBase::preInitialize() function which
// returns true.
while ( true ) {
HoldFlag<bool> hold(preinitializing, true);
ObjectSet preinits;
for ( ObjectSet::iterator it = objects().begin();
it != objects().end(); ++it )
if ( (**it).preInitialize() &&
(**it).state() == InterfacedBase::uninitialized )
preinits.insert(*it);
if ( preinits.empty() ) break;
for_each(preinits, mem_fun(&InterfacedBase::init));
}
// Initialize the quick access to particles.
theQuickParticles.clear();
theQuickParticles.resize(2*theQuickSize);
for ( ParticleMap::const_iterator pit = theParticles.begin();
pit != theParticles.end(); ++pit )
if ( abs(pit->second->id()) < theQuickSize )
theQuickParticles[pit->second->id()+theQuickSize] = pit->second;
// Then call the init method for all objects. Start with the
// standard model and the strategy.
standardModel()->init();
if ( strategy() ) strategy()->init();
eventHandler()->init();
// initialize particles first
for(ParticleMap::const_iterator pit = particles().begin();
pit != particles().end(); ++pit) pit->second->init();
for_each(objects(), mem_fun(&InterfacedBase::init));
// Then initialize the Event Handler calculating initial cross
// sections and stuff.
eventHandler()->initialize();
}
void EventGenerator::doinitrun() {
HoldFlag<int> debug(Debug::level, Debug::isset? Debug::level: theDebugLevel);
signal(SIGHUP, thepegSignalHandler);
signal(SIGINT, thepegSignalHandler);
signal(SIGTERM,thepegSignalHandler);
currentEventHandler(eventHandler());
Interfaced::doinitrun();
random().initrun();
// Then call the init method for all objects. Start with the
// standard model and the strategy.
standardModel()->initrun();
if ( strategy() ) strategy()->initrun();
// initialize particles first
for(ParticleMap::const_iterator pit = particles().begin();
pit != particles().end(); ++pit) {
pit->second->initrun();
}
eventHandler()->initrun();
for_each(objects(), mem_fun(&InterfacedBase::initrun));
if ( logNonDefault > 0 || ( ThePEG_DEBUG_LEVEL && logNonDefault == 0 ) ) {
vector< pair<IBPtr, const InterfaceBase *> > changed =
Repository::getNonDefaultInterfaces(objects());
if ( changed.size() ) {
log() << string(78, '=') << endl
<< "The following interfaces have non-default values (default):"
<< endl << string(78, '-') << endl;
for ( int i = 0, N = changed.size(); i < N; ++i ) {
log() << changed[i].first->fullName() << ":"
<< changed[i].second->name() << " = "
<< changed[i].second->exec(*changed[i].first, "notdef", "")
<< endl;
}
log() << string(78,'=') << endl;
}
}
weightSum = 0.0;
}
PDPtr EventGenerator::getParticleData(PID id) const {
long newId = id;
if ( abs(newId) < theQuickSize && theQuickParticles.size() )
return theQuickParticles[newId+theQuickSize];
ParticleMap::const_iterator it = theParticles.find(newId);
if ( it == theParticles.end() ) return PDPtr();
return it->second;
}
PPtr EventGenerator::getParticle(PID newId) const {
tcPDPtr pd = getParticleData(newId);
if ( !pd ) return PPtr();
return pd->produceParticle();
}
void EventGenerator::finalize() {
UseRandom currentRandom(theRandom);
CurrentGenerator currentGenerator(this);
finish();
finally();
}
void EventGenerator::dofinish() {
HoldFlag<int> debug(Debug::level, Debug::isset? Debug::level: theDebugLevel);
// first write out statistics from the event handler.
eventHandler()->statistics(out());
// Call the finish method for all other objects.
for_each(objects(), mem_fun(&InterfacedBase::finish));
if ( theExceptions.empty() ) {
log() << "No exceptions reported in this run.\n";
} else {
log() << "\nThe following exception classes were reported in this run:\n";
for ( ExceptionMap::iterator it = theExceptions.begin();
it != theExceptions.end(); ++it ) {
string severity;
switch ( it->first.second ) {
case Exception::info : severity="info"; break;
case Exception::warning : severity="warning"; break;
case Exception::setuperror : severity="setuperror"; break;
case Exception::eventerror : severity="eventerror"; break;
case Exception::runerror : severity="runerror"; break;
case Exception::maybeabort : severity="maybeabort"; break;
case Exception::abortnow : severity="abortnow"; break;
default : severity="unknown";
}
log() << it->first.first << ' ' << severity
<< " (" << it->second << " times)\n";
}
}
theExceptions.clear();
const string & msg = theMiscStream.str();
if ( ! msg.empty() ) {
log() << endl
<< "Miscellaneous output from modules to the standard output:\n\n"
<< msg;
theMiscStream.str("");
}
flushOutputFile();
}
void EventGenerator::finally() {
generateReferences();
closeOutputFiles();
if ( theCurrentRandom ) delete theCurrentRandom;
if ( theCurrentGenerator ) delete theCurrentGenerator;
theCurrentRandom = 0;
theCurrentGenerator = 0;
}
void EventGenerator::initialize() {
UseRandom currentRandom(theRandom);
CurrentGenerator currentGenerator(this);
doInitialize();
}
bool EventGenerator::loadMain(string file) {
initialize();
UseRandom currentRandom(theRandom);
CurrentGenerator currentGenerator(this);
Main::eventGenerator(this);
bool ok = DynamicLoader::load(file);
finish();
finally();
return ok;
}
void EventGenerator::go(long next, long maxevent, bool tics) {
UseRandom currentRandom(theRandom);
CurrentGenerator currentGenerator(this);
doGo(next, maxevent, tics);
}
EventPtr EventGenerator::shoot() {
static DebugItem debugfpu("ThePEG::FPU", 1);
if ( debugfpu ) Debug::unmaskFpuErrors();
UseRandom currentRandom(theRandom);
CurrentGenerator currentGenerator(this);
checkSignalState();
EventPtr event = doShoot();
if ( event ) weightSum += event->weight();
DebugItem::tic();
return event;
}
EventPtr EventGenerator::doShoot() {
EventPtr event;
if ( N() >= 0 && ++ieve > N() ) return event;
HoldFlag<int> debug(Debug::level, Debug::isset? Debug::level: theDebugLevel);
do {
int state = 0;
int loop = 1;
eventHandler()->clearEvent();
try {
do {
// Generate a full event or part of an event
if ( eventHandler()->empty() ) event = eventHandler()->generateEvent();
else event = eventHandler()->continueEvent();
if ( eventHandler()->empty() ) loop = -loop;
// Analyze the possibly uncomplete event
for ( AnalysisVector::iterator it = analysisHandlers().begin();
it != analysisHandlers().end(); ++it )
(**it).analyze(event, ieve, loop, state);
// Manipulate the current event, possibly deleting some steps
// and telling the event handler to redo them.
if ( manipulator() )
state = manipulator()->manipulate(eventHandler(), event);
// If the event was not completed, continue generation and continue.
loop = abs(loop) + 1;
} while ( !eventHandler()->empty() );
}
catch (Exception & ex) {
if ( logException(ex, eventHandler()->currentEvent()) ) throw;
}
catch (...) {
dump();
event = eventHandler()->currentEvent();
if ( event )
log() << *event;
else
log() << "An exception occurred before any event object was created!";
log() << endl;
throw;
}
if ( ThePEG_DEBUG_LEVEL ) {
if ( ( ThePEG_DEBUG_LEVEL == Debug::printEveryEvent ||
ieve < printEvent ) && event ) log() << *event;
if ( debugEvent > 0 && ieve + 1 >= debugEvent )
Debug::level = Debug::full;
}
} while ( !event );
// If scheduled, dump a clean state between events
if ( ThePEG_DEBUG_LEVEL && dumpPeriod > 0 && ieve%dumpPeriod == 0 ) {
eventHandler()->clearEvent();
eventHandler()->clean();
dump();
}
return event;
}
EventPtr EventGenerator::doGenerateEvent(tEventPtr e) {
if ( N() >= 0 && ++ieve > N() ) return EventPtr();
EventPtr event = e;
try {
event = eventHandler()->generateEvent(e);
}
catch (Exception & ex) {
if ( logException(ex, eventHandler()->currentEvent()) ) throw;
}
catch (...) {
dump();
event = eventHandler()->currentEvent();
if ( !event ) event = e;
log() << *event << endl;
throw;
}
return event;
}
EventPtr EventGenerator::doGenerateEvent(tStepPtr s) {
if ( N() >= 0 && ++ieve > N() ) return EventPtr();
EventPtr event;
try {
event = eventHandler()->generateEvent(s);
}
catch (Exception & ex) {
if ( logException(ex, eventHandler()->currentEvent()) ) throw;
}
catch (...) {
dump();
event = eventHandler()->currentEvent();
if ( event ) log() << *event << endl;
throw;
}
return event;
}
EventPtr EventGenerator::generateEvent(Event & e) {
UseRandom currentRandom(theRandom);
CurrentGenerator currentGenerator(this);
EventPtr event = doGenerateEvent(tEventPtr(&e));
if ( event ) weightSum += event->weight();
return event;
}
EventPtr EventGenerator::generateEvent(Step & s) {
UseRandom currentRandom(theRandom);
CurrentGenerator currentGenerator(this);
EventPtr event = doGenerateEvent(tStepPtr(&s));
if ( event ) weightSum += event->weight();
return event;
}
Energy EventGenerator::maximumCMEnergy() const {
tcEHPtr eh = eventHandler();
return eh->lumiFnPtr()? eh->lumiFn().maximumCMEnergy(): ZERO;
}
void EventGenerator::doInitialize() {
openOutputFiles();
init();
initrun();
if ( !ThePEG_DEBUG_LEVEL ) Exception::noabort = true;
}
void EventGenerator::doGo(long next, long maxevent, bool tics) {
if ( maxevent >= 0 ) N(maxevent);
if ( next >= 0 ) {
if ( tics )
cerr << "event> " << setw(9) << "init\r" << flush;
initialize();
ieve = next-1;
} else {
openOutputFiles();
}
if ( tics ) tic();
try {
while ( shoot() ) {
if ( tics ) tic();
}
}
catch ( ... ) {
finish();
throw;
}
finish();
finally();
}
void EventGenerator::tic(long currev, long totev) const {
if ( !currev ) currev = ieve;
if ( !totev ) totev = N();
long i = currev;
long n = totev;
bool skip = currev%(max(totev/100, 1L));
if ( i > n/2 ) i = n-i;
while ( skip && i >= 10 && !(i%10) ) i /= 10;
if ( i == 1 || i == 2 || i == 5 ) skip = false;
if ( skip ) return;
cerr << "event> " << setw(8) << currev << " " << setw(8) << totev << "\r";
cerr.flush();
if ( currev == totev ) cerr << endl;
}
void EventGenerator::dump() const {
if ( dumpPeriod > -1 ) {
string dumpfile;
if ( keepAllDumps ) {
ostringstream number;
number << ieve;
dumpfile = filename() + "-" + number.str() + ".dump";
}
else
dumpfile = filename() + ".dump";
PersistentOStream file(dumpfile, globalLibraries());
file << tcEGPtr(this);
}
}
void EventGenerator::use(const Interfaced & i) {
IBPtr ip = getPtr(i);
if ( ip ) usedObjects.insert(ip);
}
void EventGenerator::generateReferences() {
typedef map<string,string> StringMap;
StringMap references;
// First get all model descriptions and model references from the
// used objects. Put them in a map indexed by the description to
// avoid duplicates.
for ( ObjectSet::iterator it = usedObjects.begin();
it != usedObjects.end(); ++it ) {
if ( *it == strategy() ) continue;
string desc = Repository::getModelDescription(*it);
if ( desc.empty() ) continue;
if ( dynamic_ptr_cast<cEHPtr>(*it) ) desc = "A " + desc;
else if ( dynamic_ptr_cast<cSMPtr>(*it) ) desc = "B " + desc;
else if ( dynamic_ptr_cast<cMEPtr>(*it) ) desc = "C " + desc;
else if ( dynamic_ptr_cast<cCascHdlPtr>(*it) ) desc = "D " + desc;
else if ( dynamic_ptr_cast<cHadrHdlPtr>(*it) ) desc = "E " + desc;
else if ( dynamic_ptr_cast<cStepHdlPtr>(*it) ) desc = "F " + desc;
else if ( dynamic_ptr_cast<cDecayerPtr>(*it) ) desc = "Y " + desc;
else if ( dynamic_ptr_cast<cAnalysisHdlPtr>(*it) ) desc = "Z " + desc;
else if ( dynamic_ptr_cast<Ptr<HandlerBase>::const_pointer>(*it) )
desc = "G " + desc;
else desc = "H " + desc;
references[desc] = Repository::getModelReferences(*it);
}
// Now get the main strategy description which should put first and
// remove it from the map.
string stratdesc;
string stratref;
if ( strategy() ) {
stratdesc = Repository::getModelDescription(strategy());
stratref = Repository::getModelReferences(strategy());
references.erase(stratdesc);
}
// Open the file and write out an appendix header
if ( !useStdout )
reffile().open((filename() + ".tex").c_str());
ref() << "\\documentclass{article}\n"
<< "\\usepackage{graphics}\n"
<< "\\begin{document}\n"
<< "\\appendix\n"
<< "\\section[xxx]{\\textsc{ThePEG} version " << Repository::version()
<< " \\cite{ThePEG} Run Information}\n"
<< "Run name: \\textbf{" << runName()
<< "}:\\\\\n";
if ( !stratdesc.empty() )
ref() << "This run was generated using " << stratdesc
<< " and the following models:\n";
else
ref() << "The following models were used:\n";
ref() << "\\begin{itemize}\n";
// Write out all descriptions.
for ( StringMap::iterator it = references.begin();
it != references.end(); ++it )
ref() << "\\item " << it->first.substr(2) << endl;
// Write out thebibliography header and all references.
ref() << "\\end{itemize}\n\n"
<< "\\begin{thebibliography}{99}\n"
<< "\\bibitem{ThePEG} L.~L\\\"onnblad, "
<< "Comput.~Phys.~Commun.\\ {\\bf 118} (1999) 213.\n";
if ( !stratref.empty() ) ref() << stratref << '\n';
for ( StringMap::iterator it = references.begin();
it != references.end(); ++it )
ref() << it->second << '\n';
ref() << "\\end{thebibliography}\n"
<< "\\end{document}" << endl;
if ( !useStdout )
reffile().close();
}
void EventGenerator::strategy(StrategyPtr s) {
theStrategy = s;
}
int EventGenerator::count(const Exception & ex) {
return ++theExceptions[make_pair(StringUtils::typeName(typeid(ex)),
ex.severity())];
}
void EventGenerator::printException(const Exception & ex) {
switch ( ex.severity() ) {
case Exception::info:
log() << "* An information";
break;
case Exception::warning:
log() << "* A warning";
break;
case Exception::setuperror:
log() << "** A setup";
break;
case Exception::eventerror:
log() << "** An event";
break;
case Exception::runerror:
log() << "*** An run";
break;
case Exception::maybeabort:
case Exception::abortnow:
log() << "**** A serious";
break;
default:
log() << "**** An unknown";
break;
}
if ( ieve > 0 )
log() << " exception of type " << StringUtils::typeName(typeid(ex))
<< " occurred while generating event number "
<< ieve << ": \n" << ex.message() << endl;
else
log() << " exception occurred in the initialization of "
<< name() << ": \n" << ex.message() << endl;
if ( ex.severity() == Exception::eventerror )
log() << "The event will be discarded." << endl;
}
void EventGenerator::logWarning(const Exception & ex) {
if ( ex.severity() != Exception::info &&
ex.severity() != Exception::warning ) throw ex;
ex.handle();
int c = count(ex);
if ( c > maxWarnings ) return;
printException(ex);
if ( c == maxWarnings )
log() << "No more warnings of this kind will be reported." << endl;
}
bool EventGenerator::
logException(const Exception & ex, tcEventPtr event) {
bool noEvent = !event;
ex.handle();
int c = count(ex);
if ( c <= maxWarnings ) {
printException(ex);
if ( c == maxWarnings )
log() << "No more warnings of this kind will be reported." << endl;
}
if ( ex.severity() == Exception::info ||
ex.severity() == Exception::warning ) {
ex.handle();
return false;
}
if ( ex.severity() == Exception::eventerror ) {
if ( c < maxErrors || maxErrors <= 0 ) {
ex.handle();
if ( ThePEG_DEBUG_LEVEL > 0 && !noEvent ) log() << *event;
return false;
}
if ( c > maxErrors ) printException(ex);
log() << "Too many (" << c << ") exceptions of this kind has occurred. "
"Execution will be stopped.\n";
} else {
log() << "This exception is too serious. Execution will be stopped.\n";
}
if ( !noEvent ) log() << *event;
else log()
<< "An exception occurred before any event object was created!\n";
dump();
return true;
}
struct MatcherOrdering {
bool operator()(tcPMPtr m1, tcPMPtr m2) {
return m1->name() < m2->name() ||
( m1->name() == m2->name() && m1->fullName() < m2->fullName() );
}
};
struct ObjectOrdering {
bool operator()(tcIBPtr i1, tcIBPtr i2) {
return i1->fullName() < i2->fullName();
}
};
void EventGenerator::persistentOutput(PersistentOStream & os) const {
set<tcPMPtr,MatcherOrdering> match(theMatchers.begin(), theMatchers.end());
set<tcIBPtr,ObjectOrdering> usedset(usedObjects.begin(), usedObjects.end());
os << theDefaultObjects << theLocalParticles << theStandardModel
<< theStrategy << theRandom << theEventHandler << theAnalysisHandlers
<< theHistogramFactory << theEventManipulator << thePath << theRunName
<< theNumberOfEvents << theObjectMap << theParticles
<< theQuickParticles << theQuickSize << match << usedset
<< ieve << weightSum << theDebugLevel << logNonDefault << printEvent
<< dumpPeriod << keepAllDumps << debugEvent
<< maxWarnings << maxErrors << theCurrentEventHandler
<< theCurrentStepHandler << useStdout << theMiscStream.str();
}
void EventGenerator::persistentInput(PersistentIStream & is, int) {
string dummy;
theGlobalLibraries = is.globalLibraries();
is >> theDefaultObjects >> theLocalParticles >> theStandardModel
>> theStrategy >> theRandom >> theEventHandler >> theAnalysisHandlers
>> theHistogramFactory >> theEventManipulator >> thePath >> theRunName
>> theNumberOfEvents >> theObjectMap >> theParticles
>> theQuickParticles >> theQuickSize >> theMatchers >> usedObjects
>> ieve >> weightSum >> theDebugLevel >> logNonDefault >> printEvent
>> dumpPeriod >> keepAllDumps >> debugEvent
>> maxWarnings >> maxErrors >> theCurrentEventHandler
>> theCurrentStepHandler >> useStdout >> dummy;
theMiscStream.str(dummy);
theMiscStream.seekp(0, std::ios::end);
theObjects.clear();
for ( ObjectMap::iterator it = theObjectMap.begin();
it != theObjectMap.end(); ++it ) theObjects.insert(it->second);
}
void EventGenerator::setLocalParticles(PDPtr pd, int) {
localParticles()[pd->id()] = pd;
}
void EventGenerator::insLocalParticles(PDPtr pd, int) {
localParticles()[pd->id()] = pd;
}
void EventGenerator::delLocalParticles(int place) {
ParticleMap::iterator it = localParticles().begin();
while ( place-- && it != localParticles().end() ) ++it;
if ( it != localParticles().end() ) localParticles().erase(it);
}
vector<PDPtr> EventGenerator::getLocalParticles() const {
vector<PDPtr> ret;
for ( ParticleMap::const_iterator it = localParticles().begin();
it != localParticles().end(); ++it ) ret.push_back(it->second);
return ret;
}
void EventGenerator::setPath(string newPath) {
if ( std::system(("mkdir -p " + newPath).c_str()) ) throw EGNoPath(newPath);
if ( std::system(("touch " + newPath + "/.ThePEG").c_str()) )
throw EGNoPath(newPath);
if ( std::system(("rm -f " + newPath + "/.ThePEG").c_str()) )
throw EGNoPath(newPath);
thePath = newPath;
}
string EventGenerator::defPath() const {
char * env = std::getenv("ThePEG_RUN_DIR");
if ( env ) return string(env);
return string(".");
}
ostream & EventGenerator::out() {
return theOutStream;
}
ostream & EventGenerator::log() {
return logfile().is_open()? logfile(): BaseRepository::cout();
}
ostream & EventGenerator::ref() {
return reffile().is_open()? reffile(): BaseRepository::cout();
}
string EventGenerator::doSaveRun(string runname) {
runname = StringUtils::car(runname);
if ( runname.empty() ) runname = theRunName;
if ( runname.empty() ) runname = name();
EGPtr eg = Repository::makeRun(this, runname);
string file = eg->path() + "/" + eg->filename() + ".run";
PersistentOStream os(file);
os << eg;
if ( !os ) return "Error: Save failed! (I/O error)";
return "";
}
string EventGenerator::doMakeRun(string runname) {
runname = StringUtils::car(runname);
if ( runname.empty() ) runname = theRunName;
if ( runname.empty() ) runname = name();
Repository::makeRun(this, runname);
return "";
}
bool EventGenerator::preinitRegister(IPtr obj, string fullname) {
if ( !preinitializing ) throw InitException()
<< "Tried to register a new object in the initialization of an "
<< "EventGenerator outside of the pre-initialization face. "
<< "The preinitRegister() can only be called from a doinit() function "
<< "in an object for which preInitialize() returns true.";
if ( objectMap().find(fullname) != objectMap().end() ) return false;
obj->name(fullname);
objectMap()[fullname] = obj;
objects().insert(obj);
obj->theGenerator = this;
PDPtr pd = dynamic_ptr_cast<PDPtr>(obj);
if ( pd ) theParticles[pd->id()] = pd;
PMPtr pm = dynamic_ptr_cast<PMPtr>(obj);
if ( pm ) theMatchers.insert(pm);
return true;
}
IPtr EventGenerator::
preinitCreate(string classname, string fullname, string libraries) {
if ( !preinitializing ) throw InitException()
<< "Tried to create a new object in the initialization of an "
<< "EventGenerator outside of the pre-initialization face. "
<< "The preinitCreate() can only be called from a doinit() function "
<< "in an object for which preInitialize() returns true.";
if ( objectMap().find(fullname) != objectMap().end() ) return IPtr();
const ClassDescriptionBase * db = DescriptionList::find(classname);
while ( !db && libraries.length() ) {
string library = StringUtils::car(libraries);
libraries = StringUtils::cdr(libraries);
DynamicLoader::load(library);
db = DescriptionList::find(classname);
}
if ( !db ) return IPtr();
IPtr obj = dynamic_ptr_cast<IPtr>(db->create());
if ( !obj ) return IPtr();
if ( !preinitRegister(obj, fullname) ) return IPtr();
return obj;
}
string EventGenerator::
preinitInterface(IPtr obj, string ifcname, string cmd, string value) {
if ( !preinitializing ) throw InitException()
<< "Tried to manipulate an external object in the initialization of an "
<< "EventGenerator outside of the pre-initialization face. "
<< "The preinitSet() can only be called from a doinit() function "
<< "in an object for which preInitialize() returns true.";
if ( !obj ) return "Error: No object found.";
const InterfaceBase * ifc = Repository::FindInterface(obj, ifcname);
if ( !ifc ) return "Error: No such interface found.";
try {
return ifc->exec(*obj, cmd, value);
}
catch ( const InterfaceException & ex) {
ex.handle();
return "Error: " + ex.message();
}
}
string EventGenerator::
preinitInterface(IPtr obj, string ifcname, int index,
string cmd, string value) {
ostringstream os;
os << index;
return preinitInterface(obj, ifcname, cmd, os.str() + " " + value);
}
string EventGenerator::
preinitInterface(string fullname, string ifcname, string cmd, string value) {
return preinitInterface(getObject<Interfaced>(fullname), ifcname, cmd, value);
}
string EventGenerator::
preinitInterface(string fullname, string ifcname, int index,
string cmd, string value) {
return preinitInterface(getObject<Interfaced>(fullname), ifcname, index,
cmd, value);
}
tDMPtr EventGenerator::findDecayMode(string tag) const {
for ( ObjectSet::const_iterator it = objects().begin();
it != objects().end(); ++it ) {
tDMPtr dm = dynamic_ptr_cast<tDMPtr>(*it);
if ( dm && dm->tag() == tag ) return dm;
}
return tDMPtr();
}
tDMPtr EventGenerator::preinitCreateDecayMode(string tag) {
return constructDecayMode(tag);
}
DMPtr EventGenerator::constructDecayMode(string & tag) {
DMPtr rdm;
DMPtr adm;
int level = 0;
string::size_type end = 0;
while ( end < tag.size() && ( tag[end] != ']' || level ) ) {
switch ( tag[end++] ) {
case '[':
++level;
break;
case ']':
--level;