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 AliHLTGlobalTriggerComponentComponent 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"
39 #include "TClonesArray.h"
40 #include "TObjString.h"
42 #include "TInterpreter.h"
51 ClassImp(AliHLTGlobalTriggerComponent)
53 const char* AliHLTGlobalTriggerComponent::fgkTriggerMenuCDBPath = "HLT/ConfigHLT/HLTGlobalTrigger";
59 * This method is used as a comparison functor with the STL sort routines.
61 bool AliHLTDescendingNumbers(UInt_t a, UInt_t b)
68 AliHLTGlobalTriggerComponent::AliHLTGlobalTriggerComponent() :
72 fRuntimeCompile(true),
73 fSkipCTPCounters(false),
74 fDeleteCodeFile(false),
78 fBufferSizeConst(2*(sizeof(AliHLTGlobalTriggerDecision) + sizeof(AliHLTReadoutList))),
79 fBufferSizeMultiplier(1.),
80 fIncludePaths(TObjString::Class()),
81 fIncludeFiles(TObjString::Class())
83 // Default constructor.
85 ClearInfoForNewEvent(false);
89 AliHLTGlobalTriggerComponent::~AliHLTGlobalTriggerComponent()
91 // Default destructor.
93 if (fTrigger != NULL) delete fTrigger;
96 fCTPDecisions->Delete();
102 void AliHLTGlobalTriggerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
104 // Returns the output data size estimate.
106 constBase = fBufferSizeConst;
107 inputMultiplier = fBufferSizeMultiplier;
111 Int_t AliHLTGlobalTriggerComponent::DoInit(int argc, const char** argv)
113 // Initialises the global trigger component.
118 fDeleteCodeFile = false;
119 const char* configFileName = NULL;
120 const char* codeFileName = NULL;
121 fIncludePaths.Clear();
122 fIncludeFiles.Clear();
124 for (int i = 0; i < argc; i++)
126 if (strcmp(argv[i], "-config") == 0)
128 if (configFileName != NULL)
130 HLTWarning("Trigger configuration macro was already specified."
131 " Will replace previous value given by -config."
136 HLTError("The trigger configuration macro filename was not specified." );
139 configFileName = argv[i+1];
144 if (strcmp(argv[i], "-includepath") == 0)
148 HLTError("The include path was not specified." );
151 new (fIncludePaths[fIncludePaths.GetEntriesFast()]) TObjString(argv[i+1]);
156 if (strcmp(argv[i], "-include") == 0)
160 HLTError("The include file name was not specified." );
163 new (fIncludeFiles[fIncludeFiles.GetEntriesFast()]) TObjString(argv[i+1]);
168 if (strcmp(argv[i], "-debug") == 0)
170 if (fDebugMode == true)
172 HLTWarning("The debug flag was already specified. Ignoring this instance.");
178 if (strcmp(argv[i], "-cint") == 0)
180 fRuntimeCompile = false;
184 if (strcmp(argv[i], "-usecode") == 0)
186 if (codeFileName != NULL)
188 HLTWarning("Custom trigger code file was already specified."
189 " Will replace previous value given by -usecode."
194 HLTError("The custom trigger code filename was not specified." );
197 codeFileName = argv[i+1];
200 HLTError("The custom trigger class name was not specified." );
203 fClassName = argv[i+2];
208 if (strcmp(argv[i], "-skipctp") == 0)
210 HLTInfo("Skipping CTP counters in trigger decision");
211 fSkipCTPCounters=true;
215 HLTError("Unknown option '%s'.", argv[i]);
219 const AliHLTTriggerMenu* menu = NULL;
220 if (configFileName != NULL)
223 cmd += configFileName;
224 gROOT->ProcessLine(cmd);
225 menu = AliHLTGlobalTriggerConfig::Menu();
228 // Try load the trigger menu from the CDB if it is not loaded yet with the
230 int result = -ENOENT;
233 result = LoadTriggerMenu(fgkTriggerMenuCDBPath, menu);
237 HLTError("No trigger menu configuration found or specified.");
241 if (codeFileName == NULL)
243 result = GenerateTrigger(menu, fClassName, fCodeFileName, fIncludePaths, fIncludeFiles);
244 if (result == 0) fDeleteCodeFile = true;
248 result = LoadTriggerClass(codeFileName, fIncludePaths);
249 if (result == 0) fCodeFileName = codeFileName;
251 if (result != 0) return result;
253 fTrigger = AliHLTGlobalTrigger::CreateNew(fClassName.Data());
254 if (fTrigger == NULL)
256 HLTError("Could not create a new instance of '%s'.", fClassName.Data());
260 fTrigger->FillFromMenu(*menu);
261 if (fTrigger->CallFailed()) return -EPROTO;
263 // setup the CTP accounting in AliHLTComponent
266 // Set the default values from the trigger menu.
267 SetDescription(menu->DefaultDescription());
268 SetTriggerDomain(menu->DefaultTriggerDomain());
274 Int_t AliHLTGlobalTriggerComponent::DoDeinit()
276 // Cleans up the global trigger component.
278 if (fTrigger != NULL)
285 fCTPDecisions->Delete();
286 delete fCTPDecisions;
290 Int_t result = UnloadTriggerClass(fCodeFileName);
291 if (result != 0) return result;
293 if (fDeleteCodeFile and !fCodeFileName.IsNull() && gSystem->AccessPathName(fCodeFileName)==0 && !fDebugMode) {
294 fCodeFileName.ReplaceAll(".cxx", "*");
295 TString command="rm "; command+=fCodeFileName;
296 gSystem->Exec(command);
299 fDeleteCodeFile=false;
305 AliHLTComponent* AliHLTGlobalTriggerComponent::Spawn()
307 // Creates a new object instance.
309 return new AliHLTGlobalTriggerComponent;
313 int AliHLTGlobalTriggerComponent::DoTrigger()
315 // This method will apply the global trigger decision.
317 if (fTrigger == NULL)
319 HLTFatal("Global trigger implementation object is NULL!");
323 AliHLTUInt32_t eventType=0;
324 if (!IsDataEvent(&eventType)) {
325 if (eventType==gkAliEventTypeEndOfRun) PrintStatistics(fTrigger, kHLTLogImportant, 0);
329 // Copy the trigger counters in case we need to set them back to their original
330 // value because the PushBack method fails with ENOSPC.
331 TArrayL64 originalCounters = fTrigger->GetCounters();
332 if (fTrigger->CallFailed()) return -EPROTO;
334 fTrigger->NewEvent();
335 if (fTrigger->CallFailed()) return -EPROTO;
337 // Fill in the input data.
338 const TObject* obj = GetFirstInputObject();
341 fTrigger->Add(obj, GetDataType(), GetSpecification());
342 if (fTrigger->CallFailed()) return -EPROTO;
343 obj = GetNextInputObject();
346 // add trigger decisions for every CTP class
347 const AliHLTCTPData* pCTPData=CTPData();
349 AddCTPDecisions(fTrigger, pCTPData, GetTriggerData());
352 // Calculate the global trigger result and trigger domain, then create and push
353 // back the new global trigger decision object.
355 AliHLTTriggerDomain triggerDomain;
356 bool triggerResult = fTrigger->CalculateTriggerDecision(triggerDomain, description);
357 if (fTrigger->CallFailed()) return -EPROTO;
358 AliHLTGlobalTriggerDecision decision(
360 // The following will cause the decision to be generated with default values
361 // (set in fTriggerDomain and fDescription) if the trigger result is false.
362 (triggerResult == true) ? triggerDomain : GetTriggerDomain(),
363 (triggerResult == true) ? description.Data() : GetDescription()
366 // mask the readout list according to the CTP trigger
367 // if the classes have been initialized (mask non-zero)
368 if (pCTPData && pCTPData->Mask()) {
369 AliHLTEventDDL eventDDL=pCTPData->ReadoutList(*GetTriggerData());
370 AliHLTReadoutList ctpreadout(eventDDL);
371 ctpreadout.Enable(AliHLTReadoutList::kHLT);
372 AliHLTReadoutList maskedList=decision.ReadoutList();
373 maskedList.AndEq(ctpreadout);
374 decision.ReadoutList(maskedList);
377 decision.SetCounters(fTrigger->GetCounters(), GetEventCount()+1);
378 if (fTrigger->CallFailed()) return -EPROTO;
380 static UInt_t lastTime=0;
382 if (time.Get()-lastTime>5) {
384 PrintStatistics(fTrigger);
387 // Add the input objects used to the global decision.
388 obj = GetFirstInputObject();
391 if (obj->IsA() == AliHLTTriggerDecision::Class())
393 decision.AddTriggerInput( *static_cast<const AliHLTTriggerDecision*>(obj) );
397 decision.AddInputObject(obj);
399 obj = GetNextInputObject();
402 if (!fSkipCTPCounters && CTPData()) decision.AddInputObject(CTPData());
404 CreateEventDoneReadoutFilter(decision.TriggerDomain(), 3);
405 CreateEventDoneReadoutFilter(decision.TriggerDomain(), 4);
406 if (TriggerEvent(&decision) == -ENOSPC)
408 // Increase the estimated buffer space required if the PushBack methods in TriggerEvent
409 // returned the "no buffer space" error code. Also remember to set the trigger counters
410 // back to what they were, otherwise triggers will be double counted when we try to reprocess
411 // this event with larger buffers.
412 fBufferSizeConst += 1024*1024;
413 fBufferSizeMultiplier *= 2.;
414 fTrigger->SetCounters(originalCounters);
415 if (fTrigger->CallFailed()) return -EPROTO;
422 int AliHLTGlobalTriggerComponent::Reconfigure(const char* cdbEntry, const char* chainId)
424 // Reconfigure the component by loading the trigger menu and recreating the
425 // trigger logic class.
427 const char* path = fgkTriggerMenuCDBPath;
428 const char* id = "(unknown)";
429 if (cdbEntry != NULL) path = cdbEntry;
430 if (chainId != NULL and chainId[0] != '\0') id = chainId;
431 HLTInfo("Reconfiguring from '%s' for chain component '%s'.", path, id);
433 const AliHLTTriggerMenu* menu = NULL;
434 int result = LoadTriggerMenu(path, menu);
435 if (result != 0) return result;
438 TString codeFileName;
439 result = GenerateTrigger(menu, className, codeFileName, fIncludePaths, fIncludeFiles);
440 if (result != 0) return result;
442 AliHLTGlobalTrigger* trigger = AliHLTGlobalTrigger::CreateNew(className.Data());
445 HLTError("Could not create a new instance of '%s'.", className.Data());
446 // Make sure to cleanup after the new code file.
447 UnloadTriggerClass(codeFileName);
448 if (not codeFileName.IsNull() and gSystem->AccessPathName(codeFileName)==0 and not fDebugMode)
450 codeFileName.ReplaceAll(".cxx", "*");
451 TString command="rm "; command+=codeFileName;
452 gSystem->Exec(command);
457 if (fTrigger != NULL)
464 fTrigger->FillFromMenu(*menu);
465 if (fTrigger->CallFailed()) return -EPROTO;
467 // Set the default values from the trigger menu.
468 SetDescription(menu->DefaultDescription());
469 SetTriggerDomain(menu->DefaultTriggerDomain());
471 // Cleanup the old class code.
472 UnloadTriggerClass(fCodeFileName);
473 if (fDeleteCodeFile and not fCodeFileName.IsNull() and gSystem->AccessPathName(fCodeFileName)==0 and not fDebugMode)
475 fCodeFileName.ReplaceAll(".cxx", "*");
476 TString command="rm "; command+=fCodeFileName;
477 gSystem->Exec(command);
479 fCodeFileName = codeFileName;
480 fDeleteCodeFile = true; // Since we generated a new class.
486 int AliHLTGlobalTriggerComponent::LoadTriggerMenu(const char* cdbPath, const AliHLTTriggerMenu*& menu)
488 // Loads the trigger menu object from the CDB path.
490 HLTDebug("Trying to load trigger menu from '%s'.", cdbPath);
491 if (AliCDBManager::Instance() == NULL)
493 HLTError("CDB manager object not found.");
496 AliCDBStorage* store = AliCDBManager::Instance()->GetDefaultStorage();
499 HLTError("Could not get the the default storage for the CDB.");
502 Int_t version = store->GetLatestVersion(cdbPath, GetRunNo());
503 Int_t subVersion = store->GetLatestSubVersion(cdbPath, GetRunNo(), version);
504 AliCDBEntry* entry = AliCDBManager::Instance()->Get(cdbPath, GetRunNo(), version, subVersion);
507 HLTError("Could not get the CDB entry for \"%s\".", cdbPath);
510 TObject* obj = entry->GetObject();
513 HLTError("Configuration object for \"%s\" is missing.", cdbPath);
516 if (obj->IsA() != AliHLTTriggerMenu::Class())
518 HLTError("Wrong type for configuration object in \"%s\". Found a %s but we expect a AliHLTTriggerMenu.",
519 cdbPath, obj->ClassName()
523 menu = static_cast<AliHLTTriggerMenu*>(obj);
528 int AliHLTGlobalTriggerComponent::GenerateTrigger(
529 const AliHLTTriggerMenu* menu, TString& name, TString& filename,
530 const TClonesArray& includePaths, const TClonesArray& includeFiles
533 // Generates the global trigger class that will implement the specified trigger menu.
534 // See header for more details.
536 HLTDebug("Generating custom HLT trigger class named %s using trigger menu %p.", ((void*)menu), name.Data());
538 // Create a new UUID and replace the '-' characters with '_' to make it a valid
541 TString uuidstr = uuid.AsString();
542 for (Int_t i = 0; i < uuidstr.Length(); i++)
544 if (uuidstr[i] == '-') uuidstr[i] = '_';
547 // Create the name of the new class.
548 name = "AliHLTGlobalTriggerImpl_";
550 filename = name + ".cxx";
552 // Open a text file to write the code and generate the new class.
553 fstream code(filename.Data(), ios_base::out | ios_base::trunc);
556 HLTError("Could not open file '%s' for writing.", filename.Data());
560 TClonesArray symbols(AliHLTTriggerMenuSymbol::Class());
561 int result = BuildSymbolList(menu, symbols);
562 if (result != 0) return result;
564 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
565 code << "#include <cstring>" << endl;
566 code << "#include \"TString.h\"" << endl;
567 code << "#include \"TClonesArray.h\"" << endl;
568 code << "#include \"AliHLTLogging.h\"" << endl;
569 code << "#include \"AliHLTGlobalTrigger.h\"" << endl;
570 code << "#include \"AliHLTGlobalTriggerDecision.h\"" << endl;
571 code << "#include \"AliHLTDomainEntry.h\"" << endl;
572 code << "#include \"AliHLTTriggerDomain.h\"" << endl;
573 code << "#include \"AliHLTReadoutList.h\"" << endl;
574 code << "#include \"AliHLTTriggerMenu.h\"" << endl;
575 code << "#include \"AliHLTTriggerMenuItem.h\"" << endl;
576 code << "#include \"AliHLTTriggerMenuSymbol.h\"" << endl;
578 // Add any include files that were specified on the command line.
579 for (Int_t i = 0; i < includeFiles.GetEntriesFast(); i++)
581 TString file = static_cast<TObjString*>(includeFiles.UncheckedAt(i))->String();
582 code << "#include \"" << file.Data() << "\"" << endl;
587 code << "#else" << endl;
588 code << "const char* gFunctionName = \"???\";" << endl;
589 code << "#define HLTDebug(msg) if (CheckFilter(kHLTLogDebug) && CheckGroup(Class_Name())) SendMessage(kHLTLogDebug, Class_Name(), ::gFunctionName, __FILE__, __LINE__, msg)" << endl;
591 code << "#endif" << endl;
593 code << "class " << name << " :" << endl;
594 // Add appropriate #ifdef sections since we need to prevent inheritance from
595 // AliHLTGlobalTrigger. CINT does not seem to support multiple inheritance nor
596 // multiple levels of inheritance. Neither of the following schemes worked:
598 // 1) class AliHLTGlobalTrigger : public AliHLTLogging {};
599 // class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger {};
601 // 2) class AliHLTGlobalTrigger {};
602 // class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger, public AliHLTLogging {};
604 // Thus, we are forced to just inherit from AliHLTLogging when running in the CINT
605 // interpreter. But we anyway have to call the global trigger implementation class
606 // through the AliHLTGlobalTriggerWrapper so this is not such a problem.
607 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
608 code << " public AliHLTGlobalTrigger," << endl;
609 code << "#endif" << endl;
610 code << " public AliHLTLogging" << endl;
612 code << "public:" << endl;
614 // Generate constructor method.
615 code << " " << name << "() :" << endl;
616 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
617 code << " AliHLTGlobalTrigger()," << endl;
618 code << "#endif" << endl;
619 code << " AliHLTLogging()";
620 // Write the symbols in the trigger menu in the initialisation list.
621 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
624 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
625 code << " " << symbol->Name() << "()," << endl;
626 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
628 code << " " << symbol->Name() << "TriggerDomain()," << endl;
630 code << " " << symbol->Name() << "DomainEntry(kAliHLTAnyDataType)";
632 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
634 code << "," << endl << " fMenuItemDescription" << i << "()";
636 code << endl << " {" << endl;
639 code << "#ifdef __CINT__" << endl;
640 code << " gFunctionName = \"" << name.Data() <<"\";" << endl;
641 code << "#endif" << endl;
642 code << " SetLocalLoggingLevel(kHLTLogAll);" << endl;
643 code << " HLTDebug(Form(\"Creating new instance at %p.\", this));" << endl;
645 code << " }" << endl;
647 code << " virtual ~" << name << "() {" << endl;
650 code << "#ifdef __CINT__" << endl;
651 code << " gFunctionName = \"~" << name.Data() << "\";" << endl;
652 code << "#endif" << endl;
653 code << " HLTDebug(Form(\"Deleting instance at %p.\", this));" << endl;
655 code << " }" << endl;
657 // Generate the FillFromMenu method.
658 code << " virtual void FillFromMenu(const AliHLTTriggerMenu& menu) {" << endl;
661 code << "#ifdef __CINT__" << endl;
662 code << " gFunctionName = \"FillFromMenu\";" << endl;
663 code << "#endif" << endl;
664 code << " HLTDebug(Form(\"Filling description entries from trigger menu for global trigger %p.\", this));" << endl;
666 code << " fCounter.Set(menu.NumberOfItems());" << endl;
667 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
669 code << " fMenuItemDescription" << i << " = (menu.Item(" << i
670 << ") != NULL) ? menu.Item(" << i << ")->Description() : \"\";" << endl;
674 code << " HLTDebug(Form(\"Finished filling description entries from trigger menu.\"));" << endl;
675 code << " HLTDebug(Form(\"Filling domain entries from trigger menu symbols for global trigger %p.\", this));" << endl;
677 code << " for (Int_t i = 0; i < menu.SymbolArray().GetEntriesFast(); i++) {" << endl;
678 // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
679 // Have to use the TClass system for extra protection.
680 code << " if (menu.SymbolArray().UncheckedAt(i) == NULL) continue;" << endl;
681 code << " if (menu.SymbolArray().UncheckedAt(i)->IsA() != AliHLTTriggerMenuSymbol::Class()) continue;" << endl;
682 code << " const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const"
683 " AliHLTTriggerMenuSymbol*>(menu.SymbolArray().UncheckedAt(i));" << endl;
684 code << " if (symbol == NULL) continue;" << endl;
685 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
687 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
688 code << " if (strcmp(symbol->Name(), \"" << symbol->Name() << "\") == 0) {" << endl;
691 code << " HLTDebug(Form(\"Assinging domain entry value corresponding with symbol '%s' to '%s'.\","
692 " symbol->Name(), symbol->BlockType().AsString().Data()));" << endl;
694 code << " " << symbol->Name() << "DomainEntry = symbol->BlockType();" << endl;
695 code << " continue;" << endl;
696 code << " }" << endl;
698 code << " }" << endl;
701 code << " HLTDebug(Form(\"Finished filling domain entries from trigger menu symbols.\"));" << endl;
703 code << " }" << endl;
705 // Generate the NewEvent method.
706 code << " virtual void NewEvent() {" << endl;
709 code << "#ifdef __CINT__" << endl;
710 code << " gFunctionName = \"NewEvent\";" << endl;
711 code << "#endif" << endl;
712 code << " HLTDebug(Form(\"New event for global trigger object %p, initialising variables to default values.\", this));" << endl;
714 // Write code to initialise the symbols in the trigger menu to their default values.
715 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
717 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
718 // CINT has problems with the implicit equals operator for complex types, so if
719 // the type has a equals operater we need to write the operator call explicitly.
720 TClass* clas = TClass::GetClass(symbol->Type());
721 if (clas != NULL and clas->GetMethodAny("operator=") != NULL)
723 code << " " << symbol->Name() << ".operator = (" << symbol->DefaultValue() << ");" << endl;
727 code << " " << symbol->Name() << " = " << symbol->DefaultValue() << ";" << endl;
729 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
731 code << " " << symbol->Name() << "TriggerDomain.Clear();" << endl;
736 code << " HLTDebug(Form(\"Finished initialising variables.\"));" << endl;
738 code << " }" << endl;
740 // Generate the Add method.
741 code << " virtual void Add(const TObject* _object_, const AliHLTComponentDataType& _type_, AliHLTUInt32_t _spec_) {" << endl;
744 code << "#ifdef __CINT__" << endl;
745 code << " gFunctionName = \"Add\";" << endl;
746 code << "#endif" << endl;
748 code << " AliHLTDomainEntry _type_spec_(_type_, _spec_);" << endl;
751 code << " HLTDebug(Form(\"Adding TObject %p, with class name '%s' from data block"
752 " '%s', to global trigger object %p\", _object_, _object_->ClassName(),"
753 " _type_spec_.AsString().Data(), this));" << endl;
754 code << " _object_->Print();" << endl;
755 code << " bool _object_assigned_ = false;" << endl;
757 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
759 // Write code to check if the block type, specification and class name is correct.
760 // Then write code to assign the variable from the input object.
761 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
762 TString expr = symbol->AssignExpression();
763 if (expr == "") continue; // Skip entries that have no assignment expression.
764 bool isTrigDecision = strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0;
769 code << " HLTDebug(Form(\"Trying to match input object to class '"
770 << symbol->ObjectClass() << "', trigger name '" << symbol->RealName()
771 << "' and block type '%s'\", " << symbol->Name()
772 << "DomainEntry.AsString().Data()));" << endl;
776 code << " HLTDebug(Form(\"Trying to match input object to class '"
777 << symbol->ObjectClass() << "' and block type '%s'\", "
778 << symbol->Name() << "DomainEntry.AsString().Data()));" << endl;
781 // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
782 // Have to use the TClass system for extra protection.
783 code << " const " << symbol->ObjectClass() << "* " << symbol->Name() << "_object_ = NULL;" << endl;
784 code << " if (_object_->IsA() == " << symbol->ObjectClass() << "::Class()) " << symbol->Name()
785 << "_object_ = dynamic_cast<const " << symbol->ObjectClass()
786 << "*>(_object_);" << endl;
787 code << " if (" << symbol->Name() << "_object_ != NULL && ";
790 code << "strcmp(" << symbol->Name() << "_object_->Name(), \""
791 << symbol->Name() << "\") == 0 && ";
793 code << symbol->Name() << "DomainEntry == _type_spec_) {" << endl;
794 TString fullname = symbol->Name();
795 fullname += "_object_";
796 expr.ReplaceAll("this", fullname);
797 code << " this->" << symbol->Name() << " = " << expr.Data() << ";" << endl;
800 code << " this->" << symbol->Name() << "TriggerDomain = "
801 << fullname.Data() << "->TriggerDomain();" << endl;
805 code << " HLTDebug(Form(\"Added TObject %p with class name '%s' to variable "
806 << symbol->Name() << "\", _object_, _object_->ClassName()));" << endl;
807 code << " _object_assigned_ = true;" << endl;
809 code << " }" << endl;
813 code << " if (! _object_assigned_) {" << endl;
814 code << " HLTDebug(Form(\"Did not assign TObject %p"
815 " with class name '%s' to any variable.\", _object_, _object_->ClassName()));"
817 code << " }" << endl;
819 code << " }" << endl;
821 // Generate the CalculateTriggerDecision method.
822 // This requires code to be generated that checks which items in the trigger menu
823 // have their conditions asserted and then the trigger domain is generated from
824 // those fired items.
825 // The processing will start from the highest priority trigger group and stop
826 // after at least one trigger from the current priority group being processed
827 // is positive. For each priority group all the trigger menu items are checked.
828 // Their combined trigger condition expression must be true for the trigger priority
829 // group to be triggered positive. The full condition expression is formed by
830 // concatenating the individual condition expressions. If no trailing operators are
831 // used in the individual expressions then the default condition operator is placed
832 // between two concatenated condition expressions.
833 // If a trigger priority group has at least one trigger fired then the trigger domain
834 // is calculated such that it will give the same result as the concatenated trigger
835 // domain merging expressions for all the individual trigger menu items with
836 // positive results. Again, if no trailing operators are used in the individual
837 // merging expressions then the default domain operator is placed between two
838 // expression fragments.
839 code << " virtual bool CalculateTriggerDecision(AliHLTTriggerDomain& _domain_, TString& _description_) {" << endl;
842 code << "#ifdef __CINT__" << endl;
843 code << " gFunctionName = \"CalculateTriggerDecision\";" << endl;
844 code << "#endif" << endl;
845 code << " HLTDebug(Form(\"Calculating global HLT trigger result with trigger object at %p.\", this));" << endl;
848 // Build a list of priorities used in the trigger menu.
849 std::vector<UInt_t> priorities;
850 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
852 const AliHLTTriggerMenuItem* item = menu->Item(i);
853 bool priorityNotInList = std::find(priorities.begin(), priorities.end(), item->Priority()) == priorities.end();
854 if (priorityNotInList) priorities.push_back(item->Priority());
856 std::sort(priorities.begin(), priorities.end(), AliHLTDescendingNumbers);
857 // From the priority list, build the priority groups in the correct order,
858 // i.e. highest priority first.
859 // The priority group is a list of vectors of integers. The integers are the
860 // index numbers into the trigger menu item list for the items which form part
861 // of the priority group.
862 std::vector<std::vector<Int_t> > priorityGroup;
863 priorityGroup.insert(priorityGroup.begin(), priorities.size(), std::vector<Int_t>());
864 for (size_t n = 0; n < priorities.size(); n++)
866 UInt_t priority = priorities[n];
867 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
869 const AliHLTTriggerMenuItem* item = menu->Item(i);
870 if (item->Priority() == priority) priorityGroup[n].push_back(i);
874 for (size_t n = 0; n < priorityGroup.size(); n++)
878 code << " HLTDebug(Form(\"Processing trigger priority group " << priorities[n] << "\"));" << endl;
881 if (n == 0) code << "UInt_t ";
882 code << "_previous_match_ = 0xFFFFFFFF;" << endl;
884 if (n == 0) code << "bool ";
885 code << "_trigger_matched_ = false;" << endl;
887 if (n == 0) code << "bool ";
888 code << "_group_result_ = false;" << endl;
889 std::vector<TString> conditionOperator;
890 conditionOperator.insert(conditionOperator.begin(), priorityGroup[n].size(), TString(""));
891 std::vector<TString> domainOperator;
892 domainOperator.insert(domainOperator.begin(), priorityGroup[n].size(), TString(""));
893 for (size_t m = 0; m < priorityGroup[n].size(); m++)
895 UInt_t i = priorityGroup[n][m];
896 const AliHLTTriggerMenuItem* item = menu->Item(i);
897 TString triggerCondition = item->TriggerCondition();
898 TString mergeExpr = item->MergeExpression();
899 // Replace the symbols found in the trigger condition and merging expressions
900 // with appropriate compilable versions.
901 for (Int_t j = 0; j < symbols.GetEntriesFast(); j++)
903 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(j) );
904 bool symbolNamesDifferent = strcmp(symbol->RealName(), symbol->Name()) != 0;
905 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
907 TString newname = symbol->Name();
908 newname += "TriggerDomain";
909 mergeExpr.ReplaceAll(symbol->RealName(), newname);
913 if (symbolNamesDifferent) mergeExpr.ReplaceAll(symbol->RealName(), symbol->Name());
915 if (symbolNamesDifferent) triggerCondition.ReplaceAll(symbol->RealName(), symbol->Name());
917 // We allow the trigger conditions and merging expressions to have trailing operators.
918 // Thus, we need to extract the operators and cleanup the expressions so that they will
919 // compile. This means that we silently ignore the trailing operator if not needed.
920 if (ExtractedOperator(triggerCondition, conditionOperator[m]))
922 // If the trailing operator is the same as the default operator then reset
923 // the value in the operator list so that the default is used in the generated
924 // code. This creates more compact code.
925 if (conditionOperator[m] == menu->DefaultConditionOperator()) conditionOperator[m] = "";
927 if (ExtractedOperator(mergeExpr, domainOperator[m]))
929 if (domainOperator[m] == menu->DefaultDomainOperator()) domainOperator[m] = "";
933 code << " HLTDebug(Form(\"Trying trigger condition " << i
934 << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));"
938 if (n == 0 and m == 0) code << "bool ";
939 code << "_item_result_ = false;" << endl;
940 code << " if (" << triggerCondition << ") {" << endl;
941 code << " ++fCounter[" << i << "];" << endl;
942 const char* indentation = "";
943 if (item->PreScalar() != 0)
946 code << " if ((fCounter[" << i << "] % " << item->PreScalar() << ") == 1) {" << endl;
948 code << indentation << " _item_result_ = true;" << endl;
951 code << indentation << " HLTDebug(Form(\"Matched trigger condition " << i
952 << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));" << endl;
954 if (item->PreScalar() != 0)
956 code << " }" << endl;
958 code << " }" << endl;
961 // Since this is the first item of the trigger group,
962 // the generated trigger logic can be simplified a little.
963 code << " _group_result_ = _item_result_;" << endl;
964 code << " if (_item_result_) {" << endl;
965 code << " _domain_ = " << mergeExpr.Data() << ";" << endl;
966 code << " _description_ = fMenuItemDescription" << i << ";" << endl;
967 code << " _previous_match_ = " << i << ";" << endl;
968 code << " _trigger_matched_ = true;" << endl;
969 code << " }" << endl;
973 if (conditionOperator[m-1] == "")
975 code << " _group_result_ = _group_result_ "
976 << menu->DefaultConditionOperator() << " _item_result_;" << endl;
980 code << " _group_result_ = _group_result_ "
981 << conditionOperator[m-1] << " _item_result_;" << endl;
983 code << " if (_item_result_) {" << endl;
984 code << " if (_trigger_matched_) {" << endl;
985 bool switchWillBeEmpty = true;
986 for (size_t k = 0; k < m; k++)
988 if (domainOperator[k] == "") continue;
989 switchWillBeEmpty = false;
991 if (switchWillBeEmpty)
993 code << " _domain_ = _domain_ " << menu->DefaultDomainOperator() << " "
994 << mergeExpr.Data() << ";" << endl;
998 code << " switch(_previous_match_) {" << endl;
999 for (size_t k = 0; k < m; k++)
1001 if (domainOperator[k] == "") continue;
1002 code << " case " << k << ": _domain_ = _domain_ "
1003 << domainOperator[k] << " " << mergeExpr.Data() << "; break;" << endl;
1005 code << " default: _domain_ = _domain_ "
1006 << menu->DefaultDomainOperator() << " " << mergeExpr.Data() << ";" << endl;
1007 code << " }" << endl;
1009 code << " _description_ += \",\";" << endl;
1010 code << " _description_ += fMenuItemDescription" << i << ";" << endl;
1011 code << " } else {" << endl;
1012 code << " _domain_ = " << mergeExpr.Data() << ";" << endl;
1013 code << " _description_ = fMenuItemDescription" << i << ";" << endl;
1014 code << " }" << endl;
1015 code << " _previous_match_ = " << i << ";" << endl;
1016 code << " _trigger_matched_ = true;" << endl;
1017 code << " }" << endl;
1020 code << " if (_group_result_) {" << endl;
1023 if (n < priorities.size() - 1)
1025 code << " HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n]
1026 << ". Stopping processing here because all other trigger groups have lower priority.\"));" << endl;
1030 code << " HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n] << ".\"));" << endl;
1033 code << " return true;" << endl;
1034 code << " }" << endl;
1036 code << " _domain_.Clear();" << endl;
1037 code << " _description_ = \"\";" << endl;
1038 code << " return false;" << endl;
1039 code << " }" << endl;
1041 // Generate getter and setter methods for the counters.
1042 code << " const TArrayL64& GetCounters() const { return fCounter; }" << endl;
1043 code << " void SetCounters(const TArrayL64& counters) { fCounter = counters; }" << endl;
1045 code << "private:" << endl;
1046 // Add the symbols in the trigger menu to the list of private variables.
1047 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1049 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1050 code << " " << symbol->Type() << " " << symbol->Name() << ";" << endl;
1051 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1053 code << " AliHLTTriggerDomain " << symbol->Name() << "TriggerDomain;" << endl;
1055 code << " AliHLTDomainEntry " << symbol->Name() << "DomainEntry;" << endl;
1057 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1059 code << " TString fMenuItemDescription" << i << ";" << endl;
1061 code << " TArrayL64 fCounter;" << endl;
1062 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1063 code << " ClassDef(" << name.Data() << ", 0)" << endl;
1064 code << "#else" << endl;
1065 code << " virtual const char* Class_Name() const { return \"" << name.Data() << "\"; }" << endl;
1066 code << "#endif" << endl;
1067 code << "};" << endl;
1068 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1069 code << "ClassImp(" << name.Data() << ")" << endl;
1070 code << "#endif" << endl;
1074 // Now we need to compile and load the new class.
1075 result = LoadTriggerClass(filename, includePaths);
1080 int AliHLTGlobalTriggerComponent::LoadTriggerClass(
1081 const char* filename, const TClonesArray& includePaths
1084 // Loads the code for a custom global trigger class implementation on the fly.
1086 HLTDebug("Loading HLT trigger class from file '%s'.", filename);
1088 TString compiler = gSystem->GetBuildCompilerVersion();
1089 if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1091 TString includePath;
1092 #if defined(PKGINCLUDEDIR)
1093 // this is especially for the HLT build system where the package is installed
1094 // in a specific directory including proper treatment of include files
1095 includePath.Form("-I%s", PKGINCLUDEDIR);
1097 // the default AliRoot behavior, all include files can be found in the
1098 // $ALICE_ROOT subfolders
1099 includePath = "-I${ALICE_ROOT}/include -I${ALICE_ROOT}/HLT/BASE -I${ALICE_ROOT}/HLT/trigger";
1101 // Add any include paths that were specified on the command line.
1102 for (Int_t i = 0; i < includePaths.GetEntriesFast(); i++)
1104 TString path = static_cast<TObjString*>(includePaths.UncheckedAt(i))->String();
1105 includePath += " -I";
1106 includePath += path;
1108 HLTDebug("using include settings: %s", includePath.Data());
1109 gSystem->SetIncludePath(includePath);
1110 gSystem->SetFlagsOpt("-O3 -DNDEBUG");
1111 gSystem->SetFlagsDebug("-g3 -DDEBUG -D__DEBUG");
1116 result = gSystem->CompileMacro(filename, "g");
1120 result = gSystem->CompileMacro(filename, "O");
1122 if (result != kTRUE)
1124 HLTFatal("Could not compile and load global trigger menu implementation.");
1130 // If we do not support the compiler then try interpret the class instead.
1131 TString cmd = ".L ";
1133 Int_t errorcode = TInterpreter::kNoError;
1134 gROOT->ProcessLine(cmd, &errorcode);
1135 if (errorcode != TInterpreter::kNoError)
1137 HLTFatal("Could not load interpreted global trigger menu implementation"
1138 " (Interpreter error code = %d).",
1149 int AliHLTGlobalTriggerComponent::UnloadTriggerClass(const char* filename)
1151 // Unloads the code previously loaded by LoadTriggerClass.
1153 HLTDebug("Unloading HLT trigger class in file '%s'.", filename);
1155 TString compiler = gSystem->GetBuildCompilerVersion();
1156 if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1158 TString libname = filename;
1159 Ssiz_t dotpos = libname.Last('.');
1160 if (0 <= dotpos and dotpos < libname.Length()) libname[dotpos] = '_';
1162 libname += gSystem->GetSoExt();
1166 if ((path = gSystem->DynamicPathName(libname)) != NULL)
1168 result = gInterpreter->UnloadFile(path);
1171 if (result != TInterpreter::kNoError) return -ENOENT;
1175 // If we do not support the compiler then try interpret the class instead.
1176 TString cmd = ".U ";
1178 Int_t errorcode = TInterpreter::kNoError;
1179 gROOT->ProcessLine(cmd, &errorcode);
1180 if (errorcode != TInterpreter::kNoError)
1182 HLTFatal("Could not unload interpreted global trigger menu implementation"
1183 " (Interpreter error code = %d).",
1194 int AliHLTGlobalTriggerComponent::FindSymbol(const char* name, const TClonesArray& list)
1196 // Searches for the named symbol in the given list.
1197 // See header for more details.
1199 for (int i = 0; i < list.GetEntriesFast(); i++)
1201 const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const AliHLTTriggerMenuSymbol*>( list.UncheckedAt(i) );
1202 if (symbol == NULL) continue;
1203 if (strcmp(symbol->Name(), name) == 0) return i;
1209 int AliHLTGlobalTriggerComponent::BuildSymbolList(const AliHLTTriggerMenu* menu, TClonesArray& list)
1211 // Builds the list of symbols to use in the custom global trigger menu
1212 // implementation class.
1213 // See header for more details.
1215 for (UInt_t i = 0; i < menu->NumberOfSymbols(); i++)
1217 const AliHLTTriggerMenuSymbol* symbol = menu->Symbol(i);
1218 if (FindSymbol(symbol->Name(), list) != -1)
1220 HLTError("Multiple symbols with the name '%s' defined in the trigger menu.", symbol->Name());
1223 new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(*symbol);
1226 TRegexp exp("[_a-zA-Z][-_a-zA-Z0-9]*");
1227 TRegexp hexexp("x[a-fA-F0-9]+");
1228 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1230 const AliHLTTriggerMenuItem* item = menu->Item(i);
1231 TString str = item->TriggerCondition();
1236 Ssiz_t pos = exp.Index(str, &length, start);
1237 if (pos == kNPOS) break;
1240 // Check if there is a numerical character before the found
1241 // regular expression. If so, then the symbol is not a valid one
1242 // and should be skipped.
1245 bool notValid = false;
1248 case '0': case '1': case '2': case '3': case '4':
1249 case '5': case '6': case '7': case '8': case '9':
1256 if (notValid) continue;
1258 TString s = str(pos, length);
1260 if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1261 s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1262 s == "or_eq" or s == "xor" or s == "xor_eq" or s == "true" or
1266 // Ignore iso646.h and other keywords.
1270 if (FindSymbol(s.Data(), list) == -1)
1272 AliHLTTriggerMenuSymbol newSymbol;
1273 newSymbol.Name(s.Data());
1274 newSymbol.Type("bool");
1275 newSymbol.ObjectClass("AliHLTTriggerDecision");
1276 newSymbol.AssignExpression("this->Result()");
1277 newSymbol.DefaultValue("false");
1278 new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(newSymbol);
1281 while (start < str.Length());
1288 bool AliHLTGlobalTriggerComponent::ExtractedOperator(TString& expr, TString& op)
1290 // Extracts the trailing operator from the expression.
1293 // First skip the trailing whitespace.
1294 bool whitespace = true;
1295 for (i = expr.Length()-1; i >= 0 and whitespace; i--)
1299 case ' ': case '\t': case '\r': case '\n':
1306 if (i < 0 or whitespace) return false;
1308 // Now find the first whitespace character before the trailing symbol.
1309 bool nonwhitespace = true;
1310 for (; i >= 0 and nonwhitespace; i--)
1314 case ' ': case '\t': case '\r': case '\n':
1315 nonwhitespace = false;
1318 nonwhitespace = true;
1321 if (i < 0 or nonwhitespace) return false;
1323 // Extract the last symbols and check if it is a valid operator.
1326 if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1327 s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1328 s == "or_eq" or s == "xor" or s == "xor_eq" or s == "&&" or
1329 s == "&=" or s == "&" or s == "|" or s == "~" or s == "!" or
1330 s == "!=" or s == "||" or s == "|=" or s == "^" or s == "^=" or
1331 s == "==" or s == "+" or s == "-" or s == "*" or s == "/" or
1332 s == "%" or s == ">" or s == "<" or s == ">=" or s == "<="
1344 int AliHLTGlobalTriggerComponent::PrintStatistics(const AliHLTGlobalTrigger* pTrigger, AliHLTComponentLogSeverity level, int offset) const
1346 // print some statistics
1347 int totalEvents=GetEventCount()+offset;
1348 const TArrayL64& counters = pTrigger->GetCounters();
1349 if (pTrigger->CallFailed()) return -EPROTO;
1350 for (int i = 0; i < counters.GetSize(); i++) {
1351 ULong64_t count = counters[i];
1353 if (totalEvents>0) ratio=100*(float)count/totalEvents;
1354 HLTLog(level, "Item %d: total events: %d - counted events: %llu (%.1f%%)", i, totalEvents, count, ratio);
1359 int AliHLTGlobalTriggerComponent::AddCTPDecisions(AliHLTGlobalTrigger* pTrigger, const AliHLTCTPData* pCTPData, const AliHLTComponentTriggerData* trigData)
1361 // add trigger decisions for the valid CTP classes
1362 if (!pCTPData || !pTrigger) return 0;
1364 AliHLTUInt64_t triggerMask=pCTPData->Mask();
1365 AliHLTUInt64_t bit0=0x1;
1366 if (!fCTPDecisions) {
1367 fCTPDecisions=new TClonesArray(AliHLTTriggerDecision::Class(), gkNCTPTriggerClasses);
1368 if (!fCTPDecisions) return -ENOMEM;
1370 fCTPDecisions->ExpandCreate(gkNCTPTriggerClasses);
1371 for (int i=0; i<gkNCTPTriggerClasses; i++) {
1372 const char* name=pCTPData->Name(i);
1373 if (triggerMask&(bit0<<i) && name) {
1374 AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1377 delete fCTPDecisions;
1381 pDecision->Name(name);
1386 for (int i=0; i<gkNCTPTriggerClasses; i++) {
1387 const char* name=pCTPData->Name(i);
1388 if ((triggerMask&(bit0<<i))==0 || name==NULL) continue;
1389 AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1390 HLTDebug("updating CTP trigger decision %d %s (%p casted %p)", i, name, fCTPDecisions->At(i), pDecision);
1391 if (!pDecision) return -ENOENT;
1394 if (trigData) result=pCTPData->EvaluateCTPTriggerClass(name, *trigData);
1395 else result=pCTPData->EvaluateCTPTriggerClass(name);
1396 pDecision->Result(result);
1397 pDecision->TriggerDomain().Clear();
1398 if (trigData) pDecision->TriggerDomain().Add(pCTPData->ReadoutList(*trigData));
1399 else pDecision->TriggerDomain().Add(pCTPData->ReadoutList());
1401 pTrigger->Add(fCTPDecisions->At(i), kAliHLTDataTypeTriggerDecision, kAliHLTVoidDataSpec);
1402 if (pTrigger->CallFailed()) return -EPROTO;