2 /**************************************************************************
3 * This file is property of and copyright by the ALICE HLT Project *
4 * ALICE Experiment at CERN, All rights reserved. *
6 * Primary Authors: Artur Szostak <artursz@iafrica.com> *
7 * for The ALICE HLT Project. *
9 * Permission to use, copy, modify and distribute this software and its *
10 * documentation strictly for non-commercial purposes is hereby granted *
11 * without fee, provided that the above copyright notice appears in all *
12 * copies and that both the copyright notice and this permission notice *
13 * appear in the supporting documentation. The authors make no claims *
14 * about the suitability of this software for any purpose. It is *
15 * provided "as is" without express or implied warranty. *
16 **************************************************************************/
18 /// @file AliHLTGlobalTriggerComponent.cxx
19 /// @author Artur Szostak <artursz@iafrica.com>
21 /// @brief Implementation of the AliHLTGlobalTriggerComponent component class.
23 /// The AliHLTGlobalTriggerComponent class applies the global HLT trigger to all
24 /// trigger information produced by components deriving from AliHLTTrigger.
26 #include "AliHLTGlobalTriggerComponent.h"
27 #include "AliHLTGlobalTriggerDecision.h"
28 #include "AliHLTGlobalTrigger.h"
29 #include "AliHLTGlobalTriggerConfig.h"
30 #include "AliHLTTriggerMenu.h"
31 #include "AliHLTCTPData.h"
32 #include "AliCDBManager.h"
33 #include "AliCDBStorage.h"
34 #include "AliCDBEntry.h"
35 #include "AliRawDataHeader.h"
40 #include "TClonesArray.h"
41 #include "TObjString.h"
43 #include "TInterpreter.h"
54 ClassImp(AliHLTGlobalTriggerComponent)
56 const char* AliHLTGlobalTriggerComponent::fgkTriggerMenuCDBPath = "HLT/ConfigHLT/HLTGlobalTrigger";
62 * This method is used as a comparison functor with the STL sort routines.
64 bool AliHLTDescendingNumbers(UInt_t a, UInt_t b)
71 AliHLTGlobalTriggerComponent::AliHLTGlobalTriggerComponent() :
75 fRuntimeCompile(true),
76 fDeleteCodeFile(false),
77 fMakeSoftwareTriggers(true),
81 fBufferSizeConst(2*(sizeof(AliHLTGlobalTriggerDecision) + sizeof(AliHLTReadoutList))),
82 fBufferSizeMultiplier(1.),
83 fIncludePaths(TObjString::Class()),
84 fIncludeFiles(TObjString::Class()),
87 fDataEventsOnly(true),
90 fSoftwareTrigger(true, "SOFTWARE"),
91 fTotalEventCounter(0),
94 // Default constructor.
96 ClearInfoForNewEvent(false);
100 AliHLTGlobalTriggerComponent::~AliHLTGlobalTriggerComponent()
102 // Default destructor.
104 if (fTrigger != NULL) delete fTrigger;
107 fCTPDecisions->Delete();
108 delete fCTPDecisions;
113 void AliHLTGlobalTriggerComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& list) const
115 // Returns the kAliHLTDataTypeGlobalTrigger type as output.
116 list.push_back(kAliHLTDataTypeGlobalTrigger);
120 void AliHLTGlobalTriggerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
122 // Returns the output data size estimate.
124 constBase = fBufferSizeConst;
125 inputMultiplier = fBufferSizeMultiplier;
129 Int_t AliHLTGlobalTriggerComponent::DoInit(int argc, const char** argv)
131 // Initialises the global trigger component.
136 fDeleteCodeFile = false;
137 fMakeSoftwareTriggers = true;
138 const char* configFileName = NULL;
139 const char* codeFileName = NULL;
140 fIncludePaths.Clear();
141 fIncludeFiles.Clear();
142 SetBit(kIncludeInput);
143 fDataEventsOnly = true;
144 UInt_t randomSeed = 0;
145 bool randomSeedSet = false;
148 for (int i = 0; i < argc; i++)
150 if (strcmp(argv[i], "-config") == 0)
152 if (configFileName != NULL)
154 HLTWarning("Trigger configuration macro was already specified."
155 " Will replace previous value given by -config."
160 HLTError("The trigger configuration macro filename was not specified." );
163 configFileName = argv[i+1];
168 if (strcmp(argv[i], "-includepath") == 0)
172 HLTError("The include path was not specified." );
177 new (fIncludePaths[fIncludePaths.GetEntriesFast()]) TObjString(argv[i+1]);
179 catch (const std::bad_alloc&)
181 HLTError("Could not allocate more memory for the fIncludePaths array.");
188 if (strcmp(argv[i], "-include") == 0)
192 HLTError("The include file name was not specified." );
197 new (fIncludeFiles[fIncludeFiles.GetEntriesFast()]) TObjString(argv[i+1]);
199 catch (const std::bad_alloc&)
201 HLTError("Could not allocate more memory for the fIncludeFiles array.");
208 if (strcmp(argv[i], "-debug") == 0)
210 if (fDebugMode == true)
212 HLTWarning("The debug flag was already specified. Ignoring this instance.");
218 if (strcmp(argv[i], "-cint") == 0)
220 fRuntimeCompile = false;
224 if (strcmp(argv[i], "-usecode") == 0)
226 if (codeFileName != NULL)
228 HLTWarning("Custom trigger code file was already specified."
229 " Will replace previous value given by -usecode."
234 HLTError("The custom trigger code filename was not specified." );
237 codeFileName = argv[i+1];
240 HLTError("The custom trigger class name was not specified." );
243 fClassName = argv[i+2];
248 if (strcmp(argv[i], "-skipctp") == 0)
250 HLTInfo("Skipping CTP counters in trigger decision");
255 if (strcmp(argv[i], "-forward-input") == 0)
257 HLTInfo("Forwarding input objects and trigger decisions");
258 SetBit(kForwardInput);
259 SetBit(kIncludeShort);
260 SetBit(kIncludeInput, false);
264 if (strstr(argv[i], "-include-input") == argv[i])
266 SetBit(kForwardInput,false);
267 TString param=argv[i];
268 param.ReplaceAll("-include-input", "");
269 if (param.CompareTo("=none")==0)
271 HLTInfo("skipping objects and trigger decisions");
272 SetBit(kIncludeShort, false);
273 SetBit(kIncludeInput, false);
275 else if (param.CompareTo("=short")==0)
277 HLTInfo("including short info on objects and trigger decisions");
278 SetBit(kIncludeShort);
279 SetBit(kIncludeInput, false);
281 else if (param.CompareTo("=both")==0)
283 HLTInfo("including input objects, trigger decisions and short info");
284 SetBit(kIncludeShort);
285 SetBit(kIncludeInput);
287 else if (param.CompareTo("=objects")==0 || param.IsNull())
289 HLTInfo("including input objects and trigger decisions");
290 SetBit(kIncludeShort, false);
291 SetBit(kIncludeInput);
295 HLTError("unknown parameter '%s' for argument '-include-input'", param.Data());
300 if (strcmp(argv[i], "-process-all-events") == 0)
302 fDataEventsOnly = false;
306 if (strstr(argv[i], "-monitoring") == argv[i])
308 TString param=argv[i];
309 param.ReplaceAll("-monitoring", "");
313 // enable monitoring trigger for all events
317 // enable monitoring trigger once every n seconds
318 param.ReplaceAll("=", "");
319 if (param.IsDigit()) {
320 fMonitorPeriod=param.Atoi();
322 HLTError("expecting number as parameter for argument '-monitoring=', got %s, skipping monitoring trigger", param.Data());
328 if (strcmp(argv[i], "-dont-make-software-triggers") == 0)
330 fMakeSoftwareTriggers = false;
333 if (strcmp(argv[i], "-randomseed") == 0)
337 HLTWarning("The random seed was already specified previously with the option -randomseed."
338 "Will replace the previous value of %d with the new one.",
344 HLTError("The number to use as the seed was not specified for the -randomseed option." );
347 TString numstr = argv[i+1];
348 if (not numstr.IsDigit())
350 HLTError("The number specified in the -randomseed option is not a valid decimal integer." );
353 randomSeed = numstr.Atoi();
354 randomSeedSet = true;
359 HLTError("Unknown option '%s'.", argv[i]);
363 const AliHLTTriggerMenu* menu = NULL;
364 if (configFileName != NULL)
367 cmd += configFileName;
368 gROOT->ProcessLine(cmd);
369 menu = AliHLTGlobalTriggerConfig::Menu();
372 // Try load the trigger menu from the CDB if it is not loaded yet with the
374 int result = -ENOENT;
377 result = LoadTriggerMenu(fgkTriggerMenuCDBPath, menu);
381 HLTError("No trigger menu configuration found or specified.");
385 if (codeFileName == NULL)
387 result = GenerateTrigger(menu, fClassName, fCodeFileName, fIncludePaths, fIncludeFiles);
388 if (result == 0) fDeleteCodeFile = true;
392 result = LoadTriggerClass(codeFileName, fIncludePaths);
393 if (result == 0) fCodeFileName = codeFileName;
395 if (result != 0) return result;
399 fTrigger = AliHLTGlobalTrigger::CreateNew(fClassName.Data());
401 catch (const std::bad_alloc&)
403 HLTError("Could not allocate memory for the AliHLTGlobalTrigger instance.");
406 if (fTrigger == NULL)
408 HLTError("Could not create a new instance of '%s'.", fClassName.Data());
412 fTrigger->FillFromMenu(*menu);
413 if (fTrigger->CallFailed()) return -EPROTO;
415 // setup the CTP accounting in AliHLTComponent
418 // Set the default values from the trigger menu.
419 SetDescription(menu->DefaultDescription());
420 SetTriggerDomain(menu->DefaultTriggerDomain());
422 // Initialise the random number generator seed value.
423 // NOTE: The GenerateTrigger method called above will set the fUniqueID value
424 // with a random value based on a GUID that should be unique across the system.
425 // This is then used as the seed to the random number generator if the -randomseed
426 // option is not used.
427 if (not randomSeedSet) randomSeed = fUniqueID;
428 gRandom->SetSeed(randomSeed);
430 fTotalEventCounter = 0;
435 Int_t AliHLTGlobalTriggerComponent::DoDeinit()
437 // Cleans up the global trigger component.
439 if (fTrigger != NULL)
446 fCTPDecisions->Delete();
447 delete fCTPDecisions;
452 Int_t result = UnloadTriggerClass(fCodeFileName);
453 if (result != 0) return result;
455 if (fDeleteCodeFile and !fCodeFileName.IsNull() && gSystem->AccessPathName(fCodeFileName)==0 && !fDebugMode) {
456 fCodeFileName.ReplaceAll(".cxx", "*");
457 TString command="rm "; command+=fCodeFileName;
458 gSystem->Exec(command);
461 fDeleteCodeFile=false;
467 AliHLTComponent* AliHLTGlobalTriggerComponent::Spawn()
469 // Creates a new object instance.
470 AliHLTComponent* comp = NULL;
473 comp = new AliHLTGlobalTriggerComponent;
475 catch (const std::bad_alloc&)
477 HLTError("Could not allocate memory for a new instance of AliHLTGlobalTriggerComponent.");
484 int AliHLTGlobalTriggerComponent::DoTrigger()
486 // This method will apply the global trigger decision.
488 if (fTrigger == NULL)
490 HLTFatal("Global trigger implementation object is NULL!");
494 AliHLTUInt32_t eventType=0;
495 if (!IsDataEvent(&eventType)) {
496 if (eventType==gkAliEventTypeEndOfRun) PrintStatistics(fTrigger, kHLTLogImportant, 0);
499 IgnoreEvent(); // dont generate any trigger decision.
504 fCDH = NULL; // have to reset this in case ExtractTriggerData fails.
505 ExtractTriggerData(*GetTriggerData(), NULL, NULL, &fCDH, NULL);
507 // Copy the trigger counters in case we need to set them back to their original
508 // value because the PushBack method fails with ENOSPC.
509 TArrayL64 originalCounters = fTrigger->GetCounters();
510 if (fTrigger->CallFailed()) return -EPROTO;
512 fTrigger->NewEvent();
513 if (fTrigger->CallFailed()) return -EPROTO;
515 // Fill in the input data.
516 const TObject* obj = GetFirstInputObject();
519 fTrigger->Add(obj, GetDataType(), GetSpecification());
520 if (fTrigger->CallFailed()) return -EPROTO;
521 obj = GetNextInputObject();
524 // add trigger decisions for every CTP class
525 const AliHLTCTPData* pCTPData=CTPData();
527 AddCTPDecisions(fTrigger, pCTPData, GetTriggerData());
530 bool softwareTriggerIsValid = FillSoftwareTrigger();
531 if (softwareTriggerIsValid)
533 fTrigger->Add(&fSoftwareTrigger, kAliHLTDataTypeTriggerDecision, kAliHLTVoidDataSpec);
536 // Calculate the global trigger result and trigger domain, then create and push
537 // back the new global trigger decision object.
539 AliHLTTriggerDomain triggerDomain;
540 bool triggerResult = false;
541 bool matchedItems = fTrigger->CalculateTriggerDecision(triggerResult, triggerDomain, description);
542 if (fTrigger->CallFailed()) return -EPROTO;
543 AliHLTGlobalTriggerDecision decision(
545 // The following will cause the decision to be generated with default values
546 // (set in fTriggerDomain and fDescription) if the trigger result is false.
547 (matchedItems == true) ? triggerDomain : GetTriggerDomain(),
548 (matchedItems == true) ? description.Data() : GetDescription()
551 decision.SetUniqueID(fUniqueID);
552 decision.SetCounters(fTrigger->GetCounters(), fTotalEventCounter+1);
553 if (fTrigger->CallFailed()) return -EPROTO;
555 TClonesArray shortInfo(TNamed::Class(), GetNumberOfInputBlocks());
557 // Add the input objects used to make the global decision.
558 obj = GetFirstInputObject();
561 const AliHLTTriggerDecision* intrig = dynamic_cast<const AliHLTTriggerDecision*>(obj);
563 if (TestBit(kForwardInput)) Forward(obj);
565 if (TestBit(kIncludeInput))
569 decision.AddTriggerInput(*intrig);
573 // The const_cast should be safe in this case because the list of inputObjects
574 // will be added to the global decision with AddInputObjectRef, which only
575 // modifies the kCanDelete bit and nothing else.
576 // This is necessary since GetFirstInputObject only returns const objects.
577 decision.AddInputObjectRef( const_cast<TObject*>(obj) );
581 if (TestBit(kIncludeShort))
583 int entries = shortInfo.GetEntriesFast();
586 new (shortInfo[entries]) TNamed(obj->GetName(), obj->GetTitle());
588 catch (const std::bad_alloc&)
590 HLTError("Could not allocate more memory for the short list of input objects.");
595 shortInfo[entries]->SetBit(BIT(16)); // indicate that this is a trigger decision
596 shortInfo[entries]->SetBit(BIT(15), intrig->Result());
600 obj = GetNextInputObject();
602 if (TestBit(kIncludeShort)) decision.AddInputObjectRef(&shortInfo);
604 // The const_cast should be safe in this case because AddInputObjectRef just
605 // modifies the kCanDelete bit and nothing else.
606 if (!TestBit(kSkipCTP) && CTPData()) decision.AddInputObjectRef(const_cast<AliHLTCTPData*>(CTPData()));
608 if (softwareTriggerIsValid and TestBit(kIncludeInput)) decision.AddTriggerInput(fSoftwareTrigger);
610 static UInt_t lastTime=0;
612 if (time.Get()-lastTime>60) {
614 PrintStatistics(fTrigger, kHLTLogImportant);
617 // add readout filter to event done data
618 CreateEventDoneReadoutFilter(decision.TriggerDomain(), 3);
620 // add monitoring filter to event done data if enabled by setting
621 // a monitoring period >=0: -1 means off, 0 means for every event
622 // configured by argument '-monitoring[=n]'
623 if (fMonitorPeriod>=0) {
624 static UInt_t lastMonitorEvent=0;
626 AliHLTTriggerDomain monitoringFilter(decision.TriggerDomain());
627 if (decision.Result() &&
628 int(time.Get()-lastMonitorEvent)>fMonitorPeriod) {
629 lastMonitorEvent=time.Get();
630 // add monitoring event command for triggered events
631 CreateEventDoneReadoutFilter(decision.TriggerDomain(), 5);
633 // empty filter list if events are not triggered
634 // or within the monitoring interval
635 monitoringFilter.Clear();
637 // add monitoring filter list
638 CreateEventDoneReadoutFilter(monitoringFilter, 4);
641 // Mask the readout list according to the CTP trigger
642 // if the classes have been initialized (mask non-zero).
643 // If we are dealing with a software trigger on the other hand then
644 // mask with the participating detector list.
645 // In both cases we must make sure that HLT is part of the readout mask.
646 if (CTPData() != NULL and CTPData()->Mask() != 0x0)
648 AliHLTReadoutList readoutlist = decision.ReadoutList();
649 AliHLTReadoutList ctpreadout = CTPData()->ReadoutList(*GetTriggerData());
650 ctpreadout.Enable(AliHLTReadoutList::kHLT);
651 readoutlist.AndEq(ctpreadout);
652 decision.ReadoutList(readoutlist); // override the readout list with the masked one.
654 else if (softwareTriggerIsValid)
656 assert(fCDH != NULL);
657 AliHLTReadoutList readoutlist = decision.ReadoutList();
658 UInt_t detectors = fCDH->GetSubDetectors();
659 AliHLTReadoutList softwareReadout(Int_t(detectors | AliHLTReadoutList::kHLT));
660 readoutlist.AndEq(softwareReadout);
661 decision.ReadoutList(readoutlist); // override the readout list with the masked one.
664 if (TriggerEvent(&decision, kAliHLTDataTypeGlobalTrigger) == -ENOSPC)
666 // Increase the estimated buffer space required if the PushBack methods in TriggerEvent
667 // returned the "no buffer space" error code. Also remember to set the trigger counters
668 // back to what they were, otherwise triggers will be double counted when we try to reprocess
669 // this event with larger buffers.
670 fBufferSizeConst += 1024*1024;
671 fBufferSizeMultiplier *= 2.;
672 fTrigger->SetCounters(originalCounters);
673 if (fTrigger->CallFailed()) return -EPROTO;
677 ++fTotalEventCounter;
682 int AliHLTGlobalTriggerComponent::Reconfigure(const char* cdbEntry, const char* chainId)
684 // Reconfigure the component by loading the trigger menu and recreating the
685 // trigger logic class.
687 const char* path = fgkTriggerMenuCDBPath;
688 const char* id = "(unknown)";
689 if (cdbEntry != NULL) path = cdbEntry;
690 if (chainId != NULL and chainId[0] != '\0') id = chainId;
691 HLTInfo("Reconfiguring from '%s' for chain component '%s'.", path, id);
693 const AliHLTTriggerMenu* menu = NULL;
694 int result = LoadTriggerMenu(path, menu);
695 if (result != 0) return result;
698 TString codeFileName;
699 result = GenerateTrigger(menu, className, codeFileName, fIncludePaths, fIncludeFiles);
700 if (result != 0) return result;
702 AliHLTGlobalTrigger* trigger = NULL;
705 trigger = AliHLTGlobalTrigger::CreateNew(className.Data());
707 catch (const std::bad_alloc&)
709 HLTError("Could not allocate memory for the AliHLTGlobalTrigger instance.");
714 HLTError("Could not create a new instance of '%s'.", className.Data());
715 // Make sure to cleanup after the new code file.
716 UnloadTriggerClass(codeFileName);
717 if (not codeFileName.IsNull() and gSystem->AccessPathName(codeFileName)==0 and not fDebugMode)
719 codeFileName.ReplaceAll(".cxx", "*");
720 TString command="rm "; command+=codeFileName;
721 gSystem->Exec(command);
726 if (fTrigger != NULL)
733 fTrigger->FillFromMenu(*menu);
734 if (fTrigger->CallFailed()) return -EPROTO;
736 // Set the default values from the trigger menu.
737 SetDescription(menu->DefaultDescription());
738 SetTriggerDomain(menu->DefaultTriggerDomain());
740 // Cleanup the old class code.
741 UnloadTriggerClass(fCodeFileName);
742 if (fDeleteCodeFile and not fCodeFileName.IsNull() and gSystem->AccessPathName(fCodeFileName)==0 and not fDebugMode)
744 fCodeFileName.ReplaceAll(".cxx", "*");
745 TString command="rm "; command+=fCodeFileName;
746 gSystem->Exec(command);
748 fCodeFileName = codeFileName;
749 fDeleteCodeFile = true; // Since we generated a new class.
755 int AliHLTGlobalTriggerComponent::LoadTriggerMenu(const char* cdbPath, const AliHLTTriggerMenu*& menu)
757 // Loads the trigger menu object from the CDB path.
759 HLTDebug("Trying to load trigger menu from '%s'.", cdbPath);
760 if (AliCDBManager::Instance() == NULL)
762 HLTError("CDB manager object not found.");
765 AliCDBStorage* store = AliCDBManager::Instance()->GetDefaultStorage();
768 HLTError("Could not get the the default storage for the CDB.");
771 Int_t version = store->GetLatestVersion(cdbPath, GetRunNo());
772 Int_t subVersion = store->GetLatestSubVersion(cdbPath, GetRunNo(), version);
773 AliCDBEntry* entry = AliCDBManager::Instance()->Get(cdbPath, GetRunNo(), version, subVersion);
776 HLTError("Could not get the CDB entry for \"%s\".", cdbPath);
779 TObject* obj = entry->GetObject();
782 HLTError("Configuration object for \"%s\" is missing.", cdbPath);
785 if (obj->IsA() != AliHLTTriggerMenu::Class())
787 HLTError("Wrong type for configuration object in \"%s\". Found a %s but we expect a AliHLTTriggerMenu.",
788 cdbPath, obj->ClassName()
792 menu = static_cast<AliHLTTriggerMenu*>(obj);
797 void AliHLTGlobalTriggerComponent::GenerateFileName(TString& name, TString& filename)
799 // Creates a unique file name for the generated code.
801 TUUID guid = GenerateGUID();
808 fUniqueID = bufAsInt[0];
809 TString guidstr = guid.AsString();
810 // Replace '-' with '_' in string.
811 for (int i = 0; i < guidstr.Length(); ++i)
813 if (guidstr[i] == '-') guidstr[i] = '_';
815 name = "AliHLTGlobalTriggerImpl_";
817 filename = name + ".cxx";
819 // For good measure, check that the file names are not used. If they are then regenerate.
820 fstream file(filename.Data(), ios_base::in);
824 GenerateFileName(name, filename);
829 int AliHLTGlobalTriggerComponent::GenerateTrigger(
830 const AliHLTTriggerMenu* menu, TString& name, TString& filename,
831 const TClonesArray& includePaths, const TClonesArray& includeFiles
834 // Generates the global trigger class that will implement the specified trigger menu.
835 // See header for more details.
837 GenerateFileName(name, filename);
838 HLTDebug("Generating custom HLT trigger class named %s, in file %s, using trigger menu %p.",
839 name.Data(), filename.Data(), ((void*)menu)
842 // Open a text file to write the code and generate the new class.
843 fstream code(filename.Data(), ios_base::out | ios_base::trunc);
846 HLTError("Could not open file '%s' for writing.", filename.Data());
850 TClonesArray symbols(AliHLTTriggerMenuSymbol::Class());
851 int result = BuildSymbolList(menu, symbols);
852 if (result != 0) return result;
854 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
855 code << "#include <cstring>" << endl;
856 code << "#include \"TClass.h\"" << endl;
857 code << "#include \"TString.h\"" << endl;
858 code << "#include \"TClonesArray.h\"" << endl;
859 code << "#include \"TRandom3.h\"" << endl;
860 code << "#include \"AliHLTLogging.h\"" << endl;
861 code << "#include \"AliHLTGlobalTrigger.h\"" << endl;
862 code << "#include \"AliHLTGlobalTriggerDecision.h\"" << endl;
863 code << "#include \"AliHLTDomainEntry.h\"" << endl;
864 code << "#include \"AliHLTTriggerDomain.h\"" << endl;
865 code << "#include \"AliHLTReadoutList.h\"" << endl;
866 code << "#include \"AliHLTTriggerMenu.h\"" << endl;
867 code << "#include \"AliHLTTriggerMenuItem.h\"" << endl;
868 code << "#include \"AliHLTTriggerMenuSymbol.h\"" << endl;
870 // Add any include files that were specified on the command line.
871 for (Int_t i = 0; i < includeFiles.GetEntriesFast(); i++)
873 TString file = static_cast<TObjString*>(includeFiles.UncheckedAt(i))->String();
874 code << "#include \"" << file.Data() << "\"" << endl;
879 code << "#else" << endl;
880 code << "const char* gFunctionName = \"???\";" << endl;
881 code << "#define HLTDebug(msg) if (CheckFilter(kHLTLogDebug) && CheckGroup(Class_Name())) SendMessage(kHLTLogDebug, Class_Name(), ::gFunctionName, __FILE__, __LINE__, msg)" << endl;
883 code << "#endif" << endl;
885 code << "class " << name << " :" << endl;
886 // Add appropriate #ifdef sections since we need to prevent inheritance from
887 // AliHLTGlobalTrigger. CINT does not seem to support multiple inheritance nor
888 // multiple levels of inheritance. Neither of the following schemes worked:
890 // 1) class AliHLTGlobalTrigger : public AliHLTLogging {};
891 // class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger {};
893 // 2) class AliHLTGlobalTrigger {};
894 // class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger, public AliHLTLogging {};
896 // Thus, we are forced to just inherit from AliHLTLogging when running in the CINT
897 // interpreter. But we anyway have to call the global trigger implementation class
898 // through the AliHLTGlobalTriggerWrapper so this is not such a problem.
899 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
900 code << " public AliHLTGlobalTrigger," << endl;
901 code << "#endif" << endl;
902 code << " public AliHLTLogging" << endl;
904 code << "public:" << endl;
906 // Generate constructor method.
907 code << " " << name << "() :" << endl;
908 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
909 code << " AliHLTGlobalTrigger()," << endl;
910 code << "#endif" << endl;
911 code << " AliHLTLogging()";
912 // Write the symbols in the trigger menu in the initialisation list.
913 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
916 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
917 code << " " << symbol->Name() << "()," << endl;
918 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
920 code << " " << symbol->Name() << "TriggerDomain()," << endl;
922 code << " " << symbol->Name() << "DomainEntry(kAliHLTAnyDataType)";
924 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
926 code << "," << endl << " fMenuItemDescription" << i << "()";
928 code << endl << " {" << endl;
931 code << "#ifdef __CINT__" << endl;
932 code << " gFunctionName = \"" << name.Data() <<"\";" << endl;
933 code << "#endif" << endl;
934 code << " SetLocalLoggingLevel(kHLTLogAll);" << endl;
935 code << " HLTDebug(Form(\"Creating new instance at %p.\", this));" << endl;
937 code << " }" << endl;
939 code << " virtual ~" << name << "() {" << endl;
942 code << "#ifdef __CINT__" << endl;
943 code << " gFunctionName = \"~" << name.Data() << "\";" << endl;
944 code << "#endif" << endl;
945 code << " HLTDebug(Form(\"Deleting instance at %p.\", this));" << endl;
947 code << " }" << endl;
949 // Generate the FillFromMenu method.
950 code << " virtual void FillFromMenu(const AliHLTTriggerMenu& menu) {" << endl;
953 code << "#ifdef __CINT__" << endl;
954 code << " gFunctionName = \"FillFromMenu\";" << endl;
955 code << "#endif" << endl;
956 code << " HLTDebug(Form(\"Filling description entries from trigger menu for global trigger %p.\", this));" << endl;
958 code << " fCounter.Set(menu.NumberOfItems());" << endl;
959 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
961 code << " fMenuItemDescription" << i << " = (menu.Item(" << i
962 << ") != NULL) ? menu.Item(" << i << ")->Description() : \"\";" << endl;
966 code << " HLTDebug(Form(\"Finished filling description entries from trigger menu.\"));" << endl;
967 code << " HLTDebug(Form(\"Filling domain entries from trigger menu symbols for global trigger %p.\", this));" << endl;
969 code << " for (Int_t i = 0; i < menu.SymbolArray().GetEntriesFast(); i++) {" << endl;
970 // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
971 // Have to use the TClass system for extra protection.
972 code << " if (menu.SymbolArray().UncheckedAt(i) == NULL) continue;" << endl;
973 code << " if (menu.SymbolArray().UncheckedAt(i)->IsA() != AliHLTTriggerMenuSymbol::Class()) continue;" << endl;
974 code << " const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const"
975 " AliHLTTriggerMenuSymbol*>(menu.SymbolArray().UncheckedAt(i));" << endl;
976 code << " if (symbol == NULL) continue;" << endl;
977 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
979 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
980 code << " if (strcmp(symbol->RealName(), \"" << symbol->RealName() << "\") == 0) {" << endl;
983 code << " HLTDebug(Form(\"Assinging domain entry value corresponding with symbol '%s' to '%s'.\","
984 " symbol->RealName(), symbol->BlockType().AsString().Data()));" << endl;
986 code << " " << symbol->Name() << "DomainEntry = symbol->BlockType();" << endl;
987 code << " continue;" << endl;
988 code << " }" << endl;
990 code << " }" << endl;
991 // The following is an optimisation where symbols without any assignment operators
992 // are treated as constant and only initialised in FillFromMenu rather than reseting
993 // them in the NewEvent method.
994 // Note: we putting this initialisation into the constructor can lead to seg faults
995 // under CINT interpretation. Thus we must put it into the FillFromMenu method instead.
996 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
998 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
999 if (TString(symbol->AssignExpression()) != "") continue;
1000 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0) continue;
1001 // CINT has problems with the implicit equals operator for complex types, so if
1002 // the type has an equals operater we need to write the operator call explicitly.
1003 TClass* clas = TClass::GetClass(symbol->Type());
1004 if (clas != NULL and clas->GetMethodAny("operator=") != NULL)
1006 code << " " << symbol->Name() << ".operator = (" << symbol->DefaultValue() << ");" << endl;
1010 code << " " << symbol->Name() << " = " << symbol->DefaultValue() << ";" << endl;
1015 code << " HLTDebug(Form(\"Finished filling domain entries from trigger menu symbols.\"));" << endl;
1017 code << " }" << endl;
1019 // Generate the NewEvent method.
1020 code << " virtual void NewEvent() {" << endl;
1023 code << "#ifdef __CINT__" << endl;
1024 code << " gFunctionName = \"NewEvent\";" << endl;
1025 code << "#endif" << endl;
1026 code << " HLTDebug(Form(\"New event for global trigger object %p, initialising variables to default values.\", this));" << endl;
1028 // Write code to initialise the symbols in the trigger menu to their default values.
1029 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1031 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1032 // The following is an optimisation. If the symbol does not have an assignment expression
1033 // then it is effectively a constant symbol and can be initialised earlier and only once.
1034 // In this case we initialise it in the FillFromMenu method instead.
1035 if (TString(symbol->AssignExpression()) == "") continue;
1036 // CINT has problems with the implicit equals operator for complex types, so if
1037 // the type has an equals operater we need to write the operator call explicitly.
1038 TClass* clas = TClass::GetClass(symbol->Type());
1039 if (clas != NULL and clas->GetMethodAny("operator=") != NULL)
1041 code << " " << symbol->Name() << ".operator = (" << symbol->DefaultValue() << ");" << endl;
1045 code << " " << symbol->Name() << " = " << symbol->DefaultValue() << ";" << endl;
1047 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1049 code << " " << symbol->Name() << "TriggerDomain.Clear();" << endl;
1054 code << " HLTDebug(Form(\"Finished initialising variables.\"));" << endl;
1056 code << " }" << endl;
1058 // Generate the Add method.
1059 bool haveAssignments = false;
1060 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1062 // First check if we have any symbols with assignment expressions.
1063 // This is needed to get rid of the on the fly compilation warning about '_object_' not being used.
1064 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1065 TString expr = symbol->AssignExpression();
1066 if (expr == "") continue; // Skip entries that have no assignment expression.
1067 haveAssignments = true;
1070 if (haveAssignments or fDebugMode)
1072 code << " virtual void Add(const TObject* _object_, const AliHLTComponentDataType& _type_, AliHLTUInt32_t _spec_) {" << endl;
1076 code << " virtual void Add(const TObject* /*_object_*/, const AliHLTComponentDataType& _type_, AliHLTUInt32_t _spec_) {" << endl;
1080 code << "#ifdef __CINT__" << endl;
1081 code << " gFunctionName = \"Add\";" << endl;
1082 code << "#endif" << endl;
1084 code << " AliHLTDomainEntry _type_spec_(_type_, _spec_);" << endl;
1087 code << " HLTDebug(Form(\"Adding TObject %p, with class name '%s' from data block"
1088 " '%s', to global trigger object %p\", _object_, _object_->ClassName(),"
1089 " _type_spec_.AsString().Data(), this));" << endl;
1090 code << " _object_->Print();" << endl;
1091 code << " bool _object_assigned_ = false;" << endl;
1093 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1095 // Write code to check if the block type, specification and class name is correct.
1096 // Then write code to assign the variable from the input object.
1097 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1098 TString expr = symbol->AssignExpression();
1099 if (expr == "") continue; // Skip entries that have no assignment expression.
1100 bool isTrigDecision = strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0;
1105 code << " HLTDebug(Form(\"Trying to match input object to class '"
1106 << symbol->ObjectClass() << "', trigger name '" << symbol->RealName()
1107 << "' and block type '%s'\", " << symbol->Name()
1108 << "DomainEntry.AsString().Data()));" << endl;
1112 code << " HLTDebug(Form(\"Trying to match input object to class '"
1113 << symbol->ObjectClass() << "' and block type '%s'\", "
1114 << symbol->Name() << "DomainEntry.AsString().Data()));" << endl;
1117 // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
1118 // Have to use the TClass system for extra protection.
1119 code << " const " << symbol->ObjectClass() << "* " << symbol->Name() << "_object_ = NULL;" << endl;
1120 code << " if (_object_->InheritsFrom(" << symbol->ObjectClass() << "::Class())) " << symbol->Name()
1121 << "_object_ = dynamic_cast<const " << symbol->ObjectClass()
1122 << "*>(_object_);" << endl;
1123 code << " if (" << symbol->Name() << "_object_ != NULL && ";
1126 code << "strcmp(" << symbol->Name() << "_object_->Name(), \""
1127 << symbol->RealName() << "\") == 0 && ";
1129 code << symbol->Name() << "DomainEntry == _type_spec_) {" << endl;
1130 TString fullname = symbol->Name();
1131 fullname += "_object_";
1132 expr.ReplaceAll("this", fullname);
1133 code << " this->" << symbol->Name() << " = " << expr.Data() << ";" << endl;
1136 code << " this->" << symbol->Name() << "TriggerDomain = "
1137 << fullname.Data() << "->TriggerDomain();" << endl;
1141 code << " HLTDebug(Form(\"Added TObject %p with class name '%s' to variable "
1142 << symbol->Name() << "\", _object_, _object_->ClassName()));" << endl;
1143 code << " _object_assigned_ = true;" << endl;
1145 code << " }" << endl;
1149 code << " if (! _object_assigned_) {" << endl;
1150 code << " HLTDebug(Form(\"Did not assign TObject %p"
1151 " with class name '%s' to any variable.\", _object_, _object_->ClassName()));"
1153 code << " }" << endl;
1155 code << " }" << endl;
1157 // Generate the CalculateTriggerDecision method.
1158 // This requires code to be generated that checks which items in the trigger menu
1159 // have their conditions asserted and then the trigger domain is generated from
1160 // those fired items.
1161 // The processing will start from the highest priority trigger group and stop
1162 // after at least one trigger from the current priority group being processed
1163 // is positive. For each priority group all the trigger menu items are checked.
1164 // Their combined trigger condition expression must be true for the trigger priority
1165 // group to be triggered positive. The full condition expression is formed by
1166 // concatenating the individual condition expressions. If no trailing operators are
1167 // used in the individual expressions then the default condition operator is placed
1168 // between two concatenated condition expressions.
1169 // If a trigger priority group has at least one trigger fired then the trigger domain
1170 // is calculated such that it will give the same result as the concatenated trigger
1171 // domain merging expressions for all the individual trigger menu items with
1172 // positive results. Again, if no trailing operators are used in the individual
1173 // merging expressions then the default domain operator is placed between two
1174 // expression fragments.
1175 code << " virtual bool CalculateTriggerDecision(bool& _trigger_result_, AliHLTTriggerDomain& _domain_, TString& _description_) {" << endl;
1178 code << "#ifdef __CINT__" << endl;
1179 code << " gFunctionName = \"CalculateTriggerDecision\";" << endl;
1180 code << "#endif" << endl;
1181 code << " HLTDebug(Form(\"Calculating global HLT trigger result with trigger object at %p.\", this));" << endl;
1184 // Build a list of priorities used in the trigger menu.
1185 std::vector<UInt_t> priorities;
1186 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1188 const AliHLTTriggerMenuItem* item = menu->Item(i);
1189 bool priorityNotInList = std::find(priorities.begin(), priorities.end(), item->Priority()) == priorities.end();
1190 if (priorityNotInList) priorities.push_back(item->Priority());
1192 std::sort(priorities.begin(), priorities.end(), AliHLTDescendingNumbers);
1193 // From the priority list, build the priority groups in the correct order,
1194 // i.e. highest priority first.
1195 // The priority group is a list of vectors of integers. The integers are the
1196 // index numbers into the trigger menu item list for the items which form part
1197 // of the priority group.
1198 std::vector<std::vector<Int_t> > priorityGroup;
1199 priorityGroup.insert(priorityGroup.begin(), priorities.size(), std::vector<Int_t>());
1200 for (size_t n = 0; n < priorities.size(); n++)
1202 UInt_t priority = priorities[n];
1203 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1205 const AliHLTTriggerMenuItem* item = menu->Item(i);
1206 if (item->Priority() == priority) priorityGroup[n].push_back(i);
1210 for (size_t n = 0; n < priorityGroup.size(); n++)
1214 code << " HLTDebug(Form(\"Processing trigger priority group " << priorities[n] << "\"));" << endl;
1217 if (n == 0) code << "UInt_t ";
1218 code << "_previous_match_ = 0xFFFFFFFF;" << endl;
1220 if (n == 0) code << "bool ";
1221 code << "_trigger_matched_ = false;" << endl;
1223 if (n == 0) code << "bool ";
1224 code << "_group_result_ = false;" << endl;
1225 std::vector<TString> conditionOperator;
1226 conditionOperator.insert(conditionOperator.begin(), priorityGroup[n].size(), TString(""));
1227 std::vector<TString> domainOperator;
1228 domainOperator.insert(domainOperator.begin(), priorityGroup[n].size(), TString(""));
1229 for (size_t m = 0; m < priorityGroup[n].size(); m++)
1231 UInt_t i = priorityGroup[n][m];
1232 const AliHLTTriggerMenuItem* item = menu->Item(i);
1233 TString triggerCondition = item->TriggerCondition();
1234 TString mergeExpr = item->MergeExpression();
1235 // Replace the symbols found in the trigger condition and merging expressions
1236 // with appropriate compilable versions.
1237 for (Int_t j = 0; j < symbols.GetEntriesFast(); j++)
1239 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(j) );
1240 bool symbolNamesDifferent = strcmp(symbol->RealName(), symbol->Name()) != 0;
1241 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1243 TString newname = symbol->Name();
1244 newname += "TriggerDomain";
1245 mergeExpr.ReplaceAll(symbol->RealName(), newname);
1249 if (symbolNamesDifferent) mergeExpr.ReplaceAll(symbol->RealName(), symbol->Name());
1251 if (symbolNamesDifferent) triggerCondition.ReplaceAll(symbol->RealName(), symbol->Name());
1253 // We allow the trigger conditions and merging expressions to have trailing operators.
1254 // Thus, we need to extract the operators and cleanup the expressions so that they will
1255 // compile. This means that we silently ignore the trailing operator if not needed.
1256 if (ExtractedOperator(triggerCondition, conditionOperator[m]))
1258 // If the trailing operator is the same as the default operator then reset
1259 // the value in the operator list so that the default is used in the generated
1260 // code. This creates more compact code.
1261 if (conditionOperator[m] == menu->DefaultConditionOperator()) conditionOperator[m] = "";
1263 if (ExtractedOperator(mergeExpr, domainOperator[m]))
1265 if (domainOperator[m] == menu->DefaultDomainOperator()) domainOperator[m] = "";
1269 code << " HLTDebug(Form(\"Trying trigger condition " << i
1270 << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));"
1274 if (n == 0 and m == 0) code << "bool ";
1275 code << "_item_result_ = false;" << endl;
1276 code << " if (" << triggerCondition << ") {" << endl;
1277 code << " ++fCounter[" << i << "];" << endl;
1278 const char* indentation = "";
1279 // Generate the code to handle the prescalar and scale-down
1280 bool havePrescalar = item->PreScalar() != 0;
1281 bool haveScaledown = item->ScaleDown() < 1;
1282 if (havePrescalar or haveScaledown)
1286 if (havePrescalar) code << "(fCounter[" << i << "] % " << item->PreScalar() << ") == 1";
1287 if (havePrescalar and haveScaledown) code << " && ";
1290 std::streamsize oldprecision = code.precision(17);
1291 code << "gRandom->Rndm() < " << item->ScaleDown();
1292 code.precision(oldprecision);
1294 code << ") {" << endl;
1296 code << indentation << " _item_result_ = true;" << endl;
1299 code << indentation << " HLTDebug(Form(\"Matched trigger condition " << i
1300 << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));" << endl;
1302 if (havePrescalar or haveScaledown)
1304 code << " }" << endl;
1306 code << " }" << endl;
1309 // Since this is the first item of the trigger group,
1310 // the generated trigger logic can be simplified a little.
1311 code << " _group_result_ = _item_result_;" << endl;
1312 code << " if (_item_result_) {" << endl;
1313 code << " _domain_ = " << mergeExpr.Data() << ";" << endl;
1314 code << " _description_ = fMenuItemDescription" << i << ";" << endl;
1315 code << " _previous_match_ = " << i << ";" << endl;
1316 code << " _trigger_matched_ = true;" << endl;
1317 code << " }" << endl;
1321 if (conditionOperator[m-1] == "")
1323 code << " _group_result_ = _group_result_ "
1324 << menu->DefaultConditionOperator() << " _item_result_;" << endl;
1328 code << " _group_result_ = _group_result_ "
1329 << conditionOperator[m-1] << " _item_result_;" << endl;
1331 code << " if (_item_result_) {" << endl;
1332 code << " if (_trigger_matched_) {" << endl;
1333 bool switchWillBeEmpty = true;
1334 for (size_t k = 0; k < m; k++)
1336 if (domainOperator[k] == "") continue;
1337 switchWillBeEmpty = false;
1339 if (switchWillBeEmpty)
1341 code << " _domain_ = _domain_ " << menu->DefaultDomainOperator() << " "
1342 << mergeExpr.Data() << ";" << endl;
1346 code << " switch(_previous_match_) {" << endl;
1347 for (size_t k = 0; k < m; k++)
1349 if (domainOperator[k] == "") continue;
1350 code << " case " << k << ": _domain_ = _domain_ "
1351 << domainOperator[k] << " " << mergeExpr.Data() << "; break;" << endl;
1353 code << " default: _domain_ = _domain_ "
1354 << menu->DefaultDomainOperator() << " " << mergeExpr.Data() << ";" << endl;
1355 code << " }" << endl;
1357 code << " _description_ += \",\";" << endl;
1358 code << " _description_ += fMenuItemDescription" << i << ";" << endl;
1359 code << " } else {" << endl;
1360 code << " _domain_ = " << mergeExpr.Data() << ";" << endl;
1361 code << " _description_ = fMenuItemDescription" << i << ";" << endl;
1362 code << " }" << endl;
1363 code << " _previous_match_ = " << i << ";" << endl;
1364 code << " _trigger_matched_ = true;" << endl;
1365 code << " }" << endl;
1368 code << " if (_group_result_) {" << endl;
1371 if (n < priorities.size() - 1)
1373 code << " HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n]
1374 << ". Stopping processing here because all other trigger groups have lower priority.\"));" << endl;
1378 code << " HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n] << ".\"));" << endl;
1381 bool methodReturnResult = true;
1382 if (priorityGroup[n].size() > 0)
1384 const AliHLTTriggerMenuItem* item = menu->Item(priorityGroup[n][0]);
1385 methodReturnResult = item->DefaultResult();
1387 // Check to see if the items of the group all have the same default result.
1388 // If not then warn the user since only the first item's value will be used.
1389 for (size_t m = 1; m < priorityGroup[n].size(); m++)
1391 const AliHLTTriggerMenuItem* item = menu->Item(priorityGroup[n][m]);
1392 if (item->DefaultResult() != methodReturnResult)
1394 HLTWarning("Found items with different default results set for priority group %d."
1395 "Will only use the value from the first item.",
1401 code << " _trigger_result_ = " << (methodReturnResult ? "true" : "false") << ";" << endl;
1402 code << " return true;" << endl;
1403 code << " }" << endl;
1405 code << " _domain_.Clear();" << endl;
1406 code << " _description_ = \"\";" << endl;
1407 code << " _trigger_result_ = " << (menu->DefaultResult() ? "true" : "false") << ";" << endl;
1408 code << " return false;" << endl;
1409 code << " }" << endl;
1411 // Generate getter and setter methods for the counters.
1412 code << " const TArrayL64& GetCounters() const { return fCounter; }" << endl;
1413 code << " void SetCounters(const TArrayL64& counters) { fCounter = counters; }" << endl;
1415 code << "private:" << endl;
1416 // Add the symbols in the trigger menu to the list of private variables.
1417 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1419 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1420 code << " " << symbol->Type() << " " << symbol->Name() << ";" << endl;
1421 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1423 code << " AliHLTTriggerDomain " << symbol->Name() << "TriggerDomain;" << endl;
1425 code << " AliHLTDomainEntry " << symbol->Name() << "DomainEntry;" << endl;
1427 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1429 code << " TString fMenuItemDescription" << i << ";" << endl;
1431 code << " TArrayL64 fCounter;" << endl;
1432 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1433 code << " ClassDef(" << name.Data() << ", 0)" << endl;
1434 code << "#else" << endl;
1435 code << " virtual const char* Class_Name() const { return \"" << name.Data() << "\"; }" << endl;
1436 code << "#endif" << endl;
1437 code << "};" << endl;
1438 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1439 code << "ClassImp(" << name.Data() << ")" << endl;
1440 code << "#endif" << endl;
1444 // Now we need to compile and load the new class.
1445 result = LoadTriggerClass(filename, includePaths);
1450 int AliHLTGlobalTriggerComponent::LoadTriggerClass(
1451 const char* filename, const TClonesArray& includePaths
1454 // Loads the code for a custom global trigger class implementation on the fly.
1456 HLTDebug("Loading HLT trigger class from file '%s'.", filename);
1458 TString compiler = gSystem->GetBuildCompilerVersion();
1459 if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1461 TString includePath;
1462 #if defined(PKGINCLUDEDIR)
1463 // this is especially for the HLT build system where the package is installed
1464 // in a specific directory including proper treatment of include files
1465 includePath.Form("-I%s", PKGINCLUDEDIR);
1467 // the default AliRoot behavior, all include files can be found in the
1468 // $ALICE_ROOT subfolders
1469 includePath = "-I${ALICE_ROOT}/include -I${ALICE_ROOT}/HLT/BASE -I${ALICE_ROOT}/HLT/trigger";
1471 // Add any include paths that were specified on the command line.
1472 for (Int_t i = 0; i < includePaths.GetEntriesFast(); i++)
1474 TString path = static_cast<TObjString*>(includePaths.UncheckedAt(i))->String();
1475 includePath += " -I";
1476 includePath += path;
1478 HLTDebug("using include settings: %s", includePath.Data());
1479 gSystem->SetIncludePath(includePath);
1480 gSystem->SetFlagsOpt("-O3 -DNDEBUG");
1481 gSystem->SetFlagsDebug("-g3 -DDEBUG -D__DEBUG");
1486 result = gSystem->CompileMacro(filename, "g");
1490 result = gSystem->CompileMacro(filename, "O");
1492 if (result != kTRUE)
1494 HLTFatal("Could not compile and load global trigger menu implementation.");
1500 // Store the library state to be checked later in UnloadTriggerClass.
1501 fLibStateAtLoad = gSystem->GetLibraries();
1503 // If we do not support the compiler then try interpret the class instead.
1504 TString cmd = ".L ";
1506 Int_t errorcode = TInterpreter::kNoError;
1507 gROOT->ProcessLine(cmd, &errorcode);
1508 if (errorcode != TInterpreter::kNoError)
1510 HLTFatal("Could not load interpreted global trigger menu implementation"
1511 " (Interpreter error code = %d).",
1522 int AliHLTGlobalTriggerComponent::UnloadTriggerClass(const char* filename)
1524 // Unloads the code previously loaded by LoadTriggerClass.
1526 HLTDebug("Unloading HLT trigger class in file '%s'.", filename);
1528 TString compiler = gSystem->GetBuildCompilerVersion();
1529 if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1531 // Generate the library name.
1532 TString libname = filename;
1533 Ssiz_t dotpos = libname.Last('.');
1534 if (0 <= dotpos and dotpos < libname.Length()) libname[dotpos] = '_';
1536 libname += gSystem->GetSoExt();
1538 // This is a workaround for a problem with unloading shared libraries in ROOT.
1539 // If the trigger logic library is loaded before the libAliHLTHOMER.so library
1540 // or any other library is loaded afterwards, then during the gInterpreter->UnloadFile
1541 // call all the subsequent libraries get unloded. This means that any objects created
1542 // from classes implemented in the libAliHLTHOMER.so library will generate segfaults
1543 // since the executable code has been unloaded.
1544 // We need to check if there are any more libraries loaded after the class we
1545 // are unloading and in that case don't unload the class.
1546 TString libstring = gSystem->GetLibraries();
1547 TString token, lastlib;
1549 Int_t numOfLibs = 0, posOfLib = -1;
1550 while (libstring.Tokenize(token, from, " "))
1554 if (token.Contains(libname)) posOfLib = numOfLibs;
1556 if (numOfLibs != posOfLib)
1558 HLTWarning(Form("ROOT limitation! Cannot properly cleanup and unload the shared"
1559 " library '%s' since another library '%s' was loaded afterwards. Trying to"
1560 " unload this library will remove the others and lead to serious memory faults.",
1561 libname.Data(), lastlib.Data()
1568 if ((path = gSystem->DynamicPathName(libname)) != NULL)
1570 result = gInterpreter->UnloadFile(path);
1573 if (result != TInterpreter::kNoError) return -ENOENT;
1577 // This is again a workaround for the problem with unloading files in ROOT.
1578 // If the trigger logic class is loaded before the libAliHLTHOMER.so library
1579 // or any other library is loaded afterwards, then during the gInterpreter->UnloadFile
1580 // call all the subsequent libraries get unloded.
1581 // We need to check if the list of loaded libraries has changed since the last
1582 // call to LoadTriggerClass. If it has then don't unload the class.
1583 if (fLibStateAtLoad != gSystem->GetLibraries())
1585 TString libstring = gSystem->GetLibraries();
1588 while (libstring.Tokenize(token, from, " "))
1590 if (not fLibStateAtLoad.Contains(token)) break;
1592 HLTWarning(Form("ROOT limitation! Cannot properly cleanup and unload the file"
1593 " '%s' since another library '%s' was loaded afterwards. Trying to unload"
1594 " this file will remove the other library and lead to serious memory faults.",
1595 filename, token.Data()
1600 // If we did not compile the trigger logic then remove the interpreted class.
1601 TString cmd = ".U ";
1603 Int_t errorcode = TInterpreter::kNoError;
1604 gROOT->ProcessLine(cmd, &errorcode);
1605 if (errorcode != TInterpreter::kNoError)
1607 HLTFatal("Could not unload interpreted global trigger menu implementation"
1608 " (Interpreter error code = %d).",
1619 int AliHLTGlobalTriggerComponent::FindSymbol(const char* name, const TClonesArray& list)
1621 // Searches for the named symbol in the given list.
1622 // See header for more details.
1624 for (int i = 0; i < list.GetEntriesFast(); i++)
1626 const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const AliHLTTriggerMenuSymbol*>( list.UncheckedAt(i) );
1627 if (symbol == NULL) continue;
1628 if (strcmp(symbol->Name(), name) == 0) return i;
1637 * Helper routine to compare two trigger menu symbols to see if b is a subset of a.
1638 * \returns true if b is a subset of a or they are unrelated.
1640 bool AliHLTCheckForContainment(const AliHLTTriggerMenuSymbol* a, const AliHLTTriggerMenuSymbol* b)
1642 TString bstr = b->Name();
1643 return bstr.Contains(a->Name());
1646 } // end of namespace
1649 int AliHLTGlobalTriggerComponent::BuildSymbolList(const AliHLTTriggerMenu* menu, TClonesArray& list)
1651 // Builds the list of symbols to use in the custom global trigger menu
1652 // implementation class.
1653 // See header for more details.
1655 // Note: when we build the symbol list we must use the symbol name as returned
1656 // by the Name() method and not the RealName() method when using FindSymbol.
1657 // This is so that we avoid problems with the generated code not compiling
1658 // because names like "abc-xyz" and "abc_xyz" are synonymous.
1659 // Name() returns the converted C++ symbol name as used in the generated code.
1661 for (UInt_t i = 0; i < menu->NumberOfSymbols(); i++)
1663 const AliHLTTriggerMenuSymbol* symbol = menu->Symbol(i);
1664 if (FindSymbol(symbol->Name(), list) != -1)
1666 HLTError("Multiple symbols with the name '%s' defined in the trigger menu.", symbol->Name());
1671 new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(*symbol);
1673 catch (const std::bad_alloc&)
1675 HLTError("Could not allocate more memory for the symbols list when adding a trigger menu symbol.");
1679 Int_t initialEntryCount = list.GetEntriesFast();
1681 // Note: the \\. must not be the first element in the character class, otherwise
1682 // it is interpreted as an "any character" dot symbol.
1683 TRegexp exp("[_a-zA-Z][-\\._a-zA-Z0-9]*");
1684 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1686 const AliHLTTriggerMenuItem* item = menu->Item(i);
1687 TString str = item->TriggerCondition();
1692 Ssiz_t pos = exp.Index(str, &length, start);
1693 if (pos == kNPOS) break;
1696 // Check if there is a numerical character before the found
1697 // regular expression. If so, then the symbol is not a valid one
1698 // and should be skipped.
1701 bool notValid = false;
1704 case '0': case '1': case '2': case '3': case '4':
1705 case '5': case '6': case '7': case '8': case '9':
1712 if (notValid) continue;
1714 TString s = str(pos, length);
1716 if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1717 s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1718 s == "or_eq" or s == "xor" or s == "xor_eq" or s == "true" or
1722 // Ignore iso646.h and other keywords.
1726 // We need to handle the special case where the symbol contains a dot.
1727 // In C++ this is a dereferencing operator. So we need to check if the
1728 // current symbol we are handling starts with the same string as any of
1729 // the existing symbols defined manually in the symbols table.
1730 // If we do find such a case then revert to treating the dot as an operator
1731 // rather than part of the symbol name. i.e. skip adding the automatic symbol.
1732 bool dereferencedSymbol = false;
1733 for (int j = 0; j < initialEntryCount; j++)
1735 const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const AliHLTTriggerMenuSymbol*>( list.UncheckedAt(j) );
1736 if (symbol == NULL) continue;
1737 TString symstr = symbol->Name();
1739 if (s.BeginsWith(symstr))
1741 dereferencedSymbol = true;
1745 if (dereferencedSymbol) continue;
1747 // Need to create the symbols first and check if its name is in the list
1748 // before actually adding it to the symbols list.
1749 AliHLTTriggerMenuSymbol newSymbol;
1750 newSymbol.Name(s.Data());
1751 newSymbol.Type("bool");
1752 newSymbol.ObjectClass("AliHLTTriggerDecision");
1753 newSymbol.AssignExpression("this->Result()");
1754 newSymbol.DefaultValue("false");
1755 if (FindSymbol(newSymbol.Name(), list) == -1)
1759 new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(newSymbol);
1761 catch (const std::bad_alloc&)
1763 HLTError("Could not allocate more memory for the symbols list when adding a trigger name symbol.");
1768 while (start < str.Length());
1771 // This last part is necessary to make sure that symbols are replaced in the
1772 // trigger condition and domain merging expressions in a greedy manner.
1773 // I.e. we need to make sure that if one symbol's string representation is
1774 // contained inside another (string subset) that the longer symbol name is
1775 // always first in the symbols list.
1776 // This will work because the symbol table is traversed from first to last
1777 // element and TString::ReplaceAll is used to replace the substrings inside
1778 // the AliHLTGlobalTriggerComponent::GenerateTrigger method.
1779 std::vector<AliHLTTriggerMenuSymbol*> orderedList;
1780 for (Int_t i = 0; i < list.GetEntriesFast(); i++)
1782 orderedList.push_back( static_cast<AliHLTTriggerMenuSymbol*>(list.UncheckedAt(i)) );
1784 std::sort(orderedList.begin(), orderedList.end(), AliHLTCheckForContainment);
1785 //std::sort(orderedList.begin(), orderedList.end());
1786 // Now swap values around according to the orderedList.
1787 for (Int_t i = 0; i < list.GetEntriesFast(); i++)
1789 AliHLTTriggerMenuSymbol* target = static_cast<AliHLTTriggerMenuSymbol*>(list.UncheckedAt(i));
1790 AliHLTTriggerMenuSymbol tmp = *target;
1791 *target = *orderedList[i];
1792 *orderedList[i] = tmp;
1799 bool AliHLTGlobalTriggerComponent::ExtractedOperator(TString& expr, TString& op)
1801 // Extracts the trailing operator from the expression.
1804 // First skip the trailing whitespace.
1805 bool whitespace = true;
1806 for (i = expr.Length()-1; i >= 0 and whitespace; i--)
1810 case ' ': case '\t': case '\r': case '\n':
1817 if (i < 0 or whitespace) return false;
1819 // Now find the first whitespace character before the trailing symbol.
1820 bool nonwhitespace = true;
1821 for (; i >= 0 and nonwhitespace; i--)
1825 case ' ': case '\t': case '\r': case '\n':
1826 nonwhitespace = false;
1829 nonwhitespace = true;
1832 if (i < 0 or nonwhitespace) return false;
1834 // Extract the last symbols and check if it is a valid operator.
1837 if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1838 s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1839 s == "or_eq" or s == "xor" or s == "xor_eq" or s == "&&" or
1840 s == "&=" or s == "&" or s == "|" or s == "~" or s == "!" or
1841 s == "!=" or s == "||" or s == "|=" or s == "^" or s == "^=" or
1842 s == "==" or s == "+" or s == "-" or s == "*" or s == "/" or
1843 s == "%" or s == ">" or s == "<" or s == ">=" or s == "<="
1855 bool AliHLTGlobalTriggerComponent::FillSoftwareTrigger()
1857 // Fills the fSoftwareTrigger structure.
1859 if (fCDH == NULL) return false;
1860 UChar_t l1msg = fCDH->GetL1TriggerMessage();
1861 if ((l1msg & 0x1) == 0x0) return false; // skip physics events.
1862 // From here on everything must be a software trigger.
1863 if (((l1msg >> 2) & 0xF) == 0xE)
1865 fSoftwareTrigger.Name("START_OF_DATA");
1866 fSoftwareTrigger.Description("Generated internal start of data trigger.");
1868 else if (((l1msg >> 2) & 0xF) == 0xF)
1870 fSoftwareTrigger.Name("END_OF_DATA");
1871 fSoftwareTrigger.Description("Generated internal end of data trigger.");
1873 else if (((l1msg >> 6) & 0x1) == 0x1)
1875 fSoftwareTrigger.Name("CALIBRATION");
1876 fSoftwareTrigger.Description("Generated internal calibration trigger.");
1880 fSoftwareTrigger.Name("SOFTWARE");
1881 fSoftwareTrigger.Description("Generated internal software trigger.");
1883 UInt_t detectors = fCDH->GetSubDetectors();
1884 fSoftwareTrigger.ReadoutList( AliHLTReadoutList(Int_t(detectors)) );
1889 int AliHLTGlobalTriggerComponent::PrintStatistics(const AliHLTGlobalTrigger* pTrigger, AliHLTComponentLogSeverity level, int offset) const
1891 // print some statistics
1892 int totalEvents=GetEventCount()+offset;
1893 const TArrayL64& counters = pTrigger->GetCounters();
1894 if (pTrigger->CallFailed()) return -EPROTO;
1895 for (int i = 0; i < counters.GetSize(); i++) {
1896 ULong64_t count = counters[i];
1898 if (totalEvents>0) ratio=100*(float)count/totalEvents;
1899 HLTLog(level, "Item %d: total events: %d - counted events: %llu (%.1f%%)", i, totalEvents, count, ratio);
1904 int AliHLTGlobalTriggerComponent::AddCTPDecisions(AliHLTGlobalTrigger* pTrigger, const AliHLTCTPData* pCTPData, const AliHLTComponentTriggerData* trigData)
1906 // add trigger decisions for the valid CTP classes
1907 if (!pCTPData || !pTrigger) return 0;
1909 AliHLTUInt64_t triggerMask=pCTPData->Mask();
1910 AliHLTUInt64_t bit0=0x1;
1911 if (!fCTPDecisions) {
1914 fCTPDecisions=new TClonesArray(AliHLTTriggerDecision::Class(), gkNCTPTriggerClasses);
1916 catch (const std::bad_alloc&)
1918 HLTError("Could not allocate memory for the CTP decisions array.");
1921 if (!fCTPDecisions) return -ENOMEM;
1925 fCTPDecisions->ExpandCreate(gkNCTPTriggerClasses);
1927 catch (const std::bad_alloc&)
1929 HLTError("Could not allocate more memory for the CTP decisions array.");
1932 for (int i=0; i<gkNCTPTriggerClasses; i++) {
1933 const char* name=pCTPData->Name(i);
1934 if (triggerMask&(bit0<<i) && name) {
1935 AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1938 delete fCTPDecisions;
1942 pDecision->Name(name);
1947 for (int i=0; i<gkNCTPTriggerClasses; i++) {
1948 const char* name=pCTPData->Name(i);
1949 if ((triggerMask&(bit0<<i))==0 || name==NULL) continue;
1950 AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1951 HLTDebug("updating CTP trigger decision %d %s (%p casted %p)", i, name, fCTPDecisions->At(i), pDecision);
1952 if (!pDecision) return -ENOENT;
1955 // 13 March 2010 - Optimisation:
1956 // Dont use the EvaluateCTPTriggerClass method, which uses slow TFormula objects.
1957 AliHLTUInt64_t triggers = 0;
1958 if (trigData) triggers = pCTPData->ActiveTriggers(*trigData);
1959 else triggers = pCTPData->Triggers();
1960 result = (triggers&((AliHLTUInt64_t)0x1<<i)) ? true : false;
1961 //if (trigData) result=pCTPData->EvaluateCTPTriggerClass(name, *trigData);
1962 //else result=pCTPData->EvaluateCTPTriggerClass(name);
1963 pDecision->Result(result);
1964 pDecision->TriggerDomain().Clear();
1965 if (trigData) pDecision->TriggerDomain().Add(pCTPData->ReadoutList(*trigData));
1966 else pDecision->TriggerDomain().Add(pCTPData->ReadoutList());
1968 pTrigger->Add(fCTPDecisions->At(i), kAliHLTDataTypeTriggerDecision, kAliHLTVoidDataSpec);
1969 if (pTrigger->CallFailed()) return -EPROTO;