AliPhysics  4e47bdd (4e47bdd)
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
AliAnalysisTaskEmcalEmbeddingHelper.cxx
Go to the documentation of this file.
1 /**************************************************************************
2  * Copyright(c) 1998-2016, ALICE Experiment at CERN, All rights reserved. *
3  * *
4  * Author: The ALICE Off-line Project. *
5  * Contributors are mentioned in the code where appropriate. *
6  * *
7  * Permission to use, copy, modify and distribute this software and its *
8  * documentation strictly for non-commercial purposes is hereby granted *
9  * without fee, provided that the above copyright notice appears in all *
10  * copies and that both the copyright notice and this permission notice *
11  * appear in the supporting documentation. The authors make no claims *
12  * about the suitability of this software for any purpose. It is *
13  * provided "as is" without express or implied warranty. *
14  **************************************************************************/
15 
16 #include <string>
17 #include <sstream>
18 #include <vector>
19 #include <algorithm>
20 #include <fstream>
21 #include <iostream>
22 #include <bitset>
23 
24 #include <TFile.h>
25 #include <TMath.h>
26 #include <TRandom.h>
27 #include <TChain.h>
28 #include <TGrid.h>
29 #include <TGridResult.h>
30 #include <TSystem.h>
31 #include <TUUID.h>
32 
33 #include <AliLog.h>
34 #include <AliAnalysisManager.h>
35 #include <AliVEvent.h>
36 #include <AliAODEvent.h>
37 #include <AliESDEvent.h>
38 #include <AliMCEvent.h>
39 #include <AliInputEventHandler.h>
40 #include <AliVHeader.h>
41 #include <AliAODMCHeader.h>
42 #include <AliGenPythiaEventHeader.h>
43 
44 #include "AliEmcalList.h"
45 
47 
51 
53 
59  fCreateHisto(true),
60  fTreeName(),
61  fAnchorRun(169838),
62  fPtHardBin(-1),
63  fNPtHardBins(0),
64  fRandomEventNumberAccess(kFALSE),
65  fRandomFileAccess(kTRUE),
66  fFilePattern(""),
67  fInputFilename(""),
68  fFileListFilename(""),
69  fFilenameIndex(-1),
70  fFilenames(),
71  fTriggerMask(AliVEvent::kAny),
72  fZVertexCut(10),
73  fMaxVertexDist(999),
74  fExternalFile(0),
75  fCurrentEntry(0),
76  fLowerEntry(0),
77  fUpperEntry(0),
78  fOffset(0),
79  fMaxNumberOfFiles(0),
80  fFileNumber(0),
81  fInitializedConfiguration(false),
82  fInitializedEmbedding(false),
83  fInitializedNewFile(false),
84  fWrappedAroundTree(false),
85  fChain(nullptr),
86  fExternalEvent(nullptr),
87  fExternalHeader(nullptr),
88  fPythiaHeader(nullptr),
89  fPythiaTrials(0.),
90  fPythiaXSection(0.),
91  fPythiaPtHard(0.),
92  fHistManager(),
93  fOutput(nullptr)
94 {
95  if (fgInstance != 0) {
96  AliError("An instance of AliAnalysisTaskEmcalEmbeddingHelper already exists: it will be deleted!!!");
97  delete fgInstance;
98  }
99 
100  fgInstance = this;
101 }
102 
109  AliAnalysisTaskSE(name),
110  fCreateHisto(true),
111  fTreeName("aodTree"),
112  fAnchorRun(169838),
113  fPtHardBin(-1),
114  fNPtHardBins(0),
115  fRandomEventNumberAccess(kFALSE),
116  fRandomFileAccess(kTRUE),
117  fFilePattern(""),
118  fInputFilename(""),
119  fFileListFilename(""),
120  fFilenameIndex(-1),
121  fFilenames(),
122  fTriggerMask(AliVEvent::kAny),
123  fZVertexCut(10),
124  fMaxVertexDist(999),
125  fExternalFile(0),
126  fCurrentEntry(0),
127  fLowerEntry(0),
128  fUpperEntry(0),
129  fOffset(0),
130  fMaxNumberOfFiles(0),
131  fFileNumber(0),
132  fInitializedConfiguration(false),
133  fInitializedEmbedding(false),
134  fInitializedNewFile(false),
135  fWrappedAroundTree(false),
136  fChain(nullptr),
137  fExternalEvent(nullptr),
138  fExternalHeader(nullptr),
139  fPythiaHeader(nullptr),
140  fPythiaTrials(0.),
141  fPythiaXSection(0.),
142  fPythiaPtHard(0.),
143  fHistManager(name),
144  fOutput(nullptr)
145 {
146  if (fgInstance != 0) {
147  AliError("An instance of AliAnalysisTaskEmcalEmbeddingHelper already exists: it will be deleted!!!");
148  delete fgInstance;
149  }
150 
151  fgInstance = this;
152 
153  if (fCreateHisto) {
154  DefineOutput(1, AliEmcalList::Class());
155  }
156 }
157 
164 {
165  if (fgInstance == this) fgInstance = 0;
166  if (fExternalEvent) delete fExternalEvent;
167  if (fExternalFile) {
168  fExternalFile->Close();
169  delete fExternalFile;
170  }
171 }
172 
178 {
179  // Get file list
180  bool result = GetFilenames();
181 
182  if (result) {
184  }
185 
186  return result;
187 }
188 
213 {
214  // Determine the pattern filename if not yet set
215  if (fInputFilename == "") {
216  if (fTreeName == "aodTree") {
217  fInputFilename = "AliAOD.root";
218  }
219  else if (fTreeName == "esdTree") {
220  fInputFilename = "AliESDs.root";
221  }
222  else {
223  AliFatal(TString::Format("Requested default (pattern) input filename, but could not determine file type from tree name \"%s\". Please check the tree name and set the pattern input filename", fTreeName.Data()));
224  }
225  }
226 
227  // Retrieve filenames if we don't have them yet.
228  if (fFilenames.size() == 0)
229  {
230  // Handle if fPtHardBin or fAnchorRun are set
231  // This will require formatting the file pattern in the proper way to support these substitutions
232  if (fPtHardBin != -1 && fFilePattern != "") {
233  if (fAnchorRun > 0) {
234  fFilePattern = TString::Format(fFilePattern, fAnchorRun, fPtHardBin);
235  }
236  else {
237  fFilePattern = TString::Format(fFilePattern, fPtHardBin);
238  }
239  }
240 
241  // Setup AliEn access if needed
242  if (fFilePattern.Contains("alien://") || fFileListFilename.Contains("alien://")) {
243  if (!gGrid) {
244  AliInfo("Trying to connect to AliEn ...");
245  TGrid::Connect("alien://");
246  }
247  if (!gGrid) {
248  AliFatal(TString::Format("Cannot access AliEn to retrieve file list with pattern %s!", fFilePattern.Data()));
249  }
250  }
251 
252  // Retrieve AliEn filenames directly from AliEn
253  bool usedFilePattern = false;
254  if (fFilePattern.Contains("alien://")) {
255  usedFilePattern = true;
256  AliDebug(2, TString::Format("Trying to retrieve file list from AliEn with pattern file %s...", fFilePattern.Data()));
257 
258  // Create a temporary filename based on a UUID to make sure that it doesn't overwrite any files
259  if (fFileListFilename == "") {
261  }
262 
263  // The query command cannot handle "alien://" in the file pattern, so we need to remove it for the command
264  TString filePattern = fFilePattern;
265  filePattern.ReplaceAll("alien://", "");
266 
267  // Execute the grid query to get the filenames
268  AliDebug(2, TString::Format("Trying to retrieve file list from AliEn with pattern \"%s\" and input filename \"%s\"", filePattern.Data(), fInputFilename.Data()));
269  auto result = gGrid->Query(filePattern.Data(), fInputFilename.Data());
270 
271  if (result) {
272  // Loop over the result to store it in the fileList file
273  std::ofstream outFile(fFileListFilename);
274  for (int i = 0; i < result->GetEntries(); i++)
275  {
276  // "turl" corresponds to the full AliEn url
277  outFile << result->GetKey(i, "turl") << "\n";
278  }
279  outFile.close();
280  }
281  else {
282  AliErrorStream() << "Failed to run grid query\n";
283  return false;
284  }
285  }
286 
287  // Handle a filelist on AliEn
288  if (fFileListFilename.Contains("alien://")) {
289  // Check if we already used the file pattern
290  if (usedFilePattern) {
291  AliErrorStream() << "You set both the file pattern and the file list filename! The file list filename will override the pattern! Pattern: \"" << fFilePattern << "\", filename: \"" << fFileListFilename << "\"\nPlease check that this is the desired behavior!\n";
292  }
293 
294  // Determine the local filename and copy file to local directory
295  std::string alienFilename = fFileListFilename.Data();
296  fFileListFilename = gSystem->BaseName(alienFilename.c_str());
298 
299  TFile::Cp(alienFilename.c_str(), fFileListFilename.Data());
300  }
301 
302  std::ifstream inputFile(fFileListFilename);
303 
304  // Copy available files into the filenames vector
305  // From:: https://stackoverflow.com/a/8365247
306  std::copy(std::istream_iterator<std::string>(inputFile),
307  std::istream_iterator<std::string>(),
308  std::back_inserter(fFilenames));
309 
310  inputFile.close();
311  }
312 
313  if (fFilenames.size() == 0) {
314  AliFatal(TString::Format("Filenames from pattern \"%s\" and file list \"%s\" yielded an empty list!", fFilePattern.Data(), fFileListFilename.Data()));
315  }
316 
317  // Add "#" to files in there are any zip files
318  // It is require to open the proper root file within the zip
319  for (auto filename : fFilenames)
320  {
321  if (filename.find(".zip") != std::string::npos && filename.find("#") == std::string::npos) {
322  filename += "#";
324  if (fTreeName == "aodTree") {
325  filename += "#AliAOD.root";
326  }
327  else if (fTreeName == "esdTree") {
328  filename += "#AliESDs.root";
329  }
330  else {
331  AliError(TString::Format("Filename %s contains \".zip\" and not \"#\", but tree name %s is not recognized. Please check the file list to ensure that the proper path is set.", filename.c_str(), fTreeName.Data()));
332  return false;
333  }
334  }
335  }
336 
337  AliInfoStream() << "Found " << fFilenames.size() << " files to embed\n";
338  return true;
339 }
340 
349 {
350  std::string tempStr = "";
351  if (fFileListFilename == "") {
352  tempStr = "fileList";
353  }
354  TUUID tempUUID;
355  tempStr += ".";
356  tempStr += tempUUID.AsString();
357  tempStr += ".txt";
358 
359  return tempStr;
360 }
361 
367 {
368  // This determines which file is added first to the TChain, thus determining the order of processing
369  // Random file access. Only do this if the user has no set the filename index and request random file access
370  if (fFilenameIndex == -1 && fRandomFileAccess) {
371  // - 1 ensures that we it doesn't overflow
372  fFilenameIndex = TMath::Nint(gRandom->Rndm()*fFilenames.size()) - 1;
373  AliInfo(TString::Format("Starting with random file number %i!", fFilenameIndex));
374  }
375  // If not random file access, then start from the beginning
376  if (fFilenameIndex >= fFilenames.size() || fFilenameIndex < 0) {
377  // Skip notifying on -1 since it will likely be set there due to constructor.
378  if (fFilenameIndex != -1) {
379  AliWarning(TString::Format("File index %i out of range from 0 to %lu! Resetting to 0!", fFilenameIndex, fFilenames.size()));
380  }
381  fFilenameIndex = 0;
382  }
383 
384  AliInfo(TString::Format("Starting with file number %i out of %lu", fFilenameIndex, fFilenames.size()));
385 }
386 
396 {
397  Int_t attempts = -1;
398 
399  do {
400  // Reset to start of tree
401  if (fCurrentEntry == fUpperEntry) {
403  fWrappedAroundTree = true;
404  }
405 
407  // Continue with GetEntry as normal
408  }
409  else {
410  // NOTE: On transition from one file to the next, this calls the next entry that would be expected.
411  // However, if it is for the last file, it tries to GetEntry() of one entry past the end of the last file.
412  // Normally, this would be a problem, however GetEntry() just doesn't fill the fields of an invalid index
413  // instead of throwing an error. So "invalid values" are filled for a file that doesn't exist, but then
414  // they are immediately replaced by the lines below that reset the access values and re-init the tree.
415  // The benefit of this approach is it simplies file counting (we don't need to carefully increment here
416  // and in InitTree()) and preserves the desired behavior when we are not at the last file.
417  InitTree();
418  }
419 
420  // Load current event
421  // Can be a simple less than, because fFileNumber counts from 0.
423  fChain->GetEntry(fCurrentEntry);
424  }
425  else {
426  AliError("====================================================================================================");
427  AliError("== No more files available to embed from the TChain! Restarting from the beginning of the TChain! ==");
428  AliError("== Be careful to check that this is the desired action! ==");
429  AliError("====================================================================================================");
430 
431  // Reset the relevant access values
432  // fCurrentEntry and fLowerEntry are automatically reset in InitTree()
433  fFileNumber = 0;
434  fUpperEntry = 0;
435 
436  // Re-init back to the start
437  InitTree();
438 
439  // Access the relevant entry
440  // We are certain that fFileNumber is less than fMaxNumberOfFiles, so we are resetting to start
441  fChain->GetEntry(fCurrentEntry);
442  }
443  AliDebug(4, TString::Format("Loading entry %i between %i-%i, starting with offset %i from the lower bound of %i", fCurrentEntry, fLowerEntry, fUpperEntry, fOffset, fLowerEntry));
444 
445  // Set relevant event properties
447 
448  // Increment current entry
449  fCurrentEntry++;
450 
451  // Provide a check for number of attempts
452  attempts++;
453  if (attempts == 1000)
454  AliWarning("After 1000 attempts no event has been accepted by the event selection (trigger, centrality...)!");
455 
456  // Record event properties
457  if (fCreateHisto) {
459  }
460 
461  } while (!IsEventSelected());
462 
463  if (fCreateHisto) {
464  fHistManager.FillTH1("fHistEventCount", "Accepted");
465  fHistManager.FillTH1("fHistEmbeddingEventsRejected", attempts);
466  }
467 
468  if (!fChain) return kFALSE;
469 
470  return kTRUE;
471 }
472 
474 {
475  AliDebug(4, "Set event properties");
476  fExternalHeader = fExternalEvent->GetHeader();
477 
478  // Handle pythia header if AOD
479  AliAODMCHeader* aodMCH = dynamic_cast<AliAODMCHeader*>(fExternalEvent->FindListObject(AliAODMCHeader::StdBranchName()));
480  if (aodMCH) {
481  for (UInt_t i = 0;i<aodMCH->GetNCocktailHeaders();i++) {
482  fPythiaHeader = dynamic_cast<AliGenPythiaEventHeader*>(aodMCH->GetCocktailHeader(i));
483  if (fPythiaHeader) break;
484  }
485  }
486 
487  if (fPythiaHeader)
488  {
489  fPythiaTrials = fPythiaHeader->Trials();
490  fPythiaXSection = fPythiaHeader->GetXsection();
491  fPythiaPtHard = fPythiaHeader->GetPtHard();
492 
493  AliDebugStream(4) << "Pythia header is defined!\n";
494  AliDebugStream(4) << "fPythiaXSection: " << fPythiaXSection << "\n";
495  }
496 }
497 
502 {
503  // Fill trials, xsec, pt hard
504  fHistManager.FillTH1("fHistTrials", fPtHardBin, fPythiaTrials);
506  fHistManager.FillTH1("fHistPtHard", fPythiaPtHard);
507 
508  // Keep count of the total number of events
509  fHistManager.FillTH1("fHistEventCount", "Total");
510 }
511 
518 {
519  // Trigger selection
520  if (fTriggerMask != AliVEvent::kAny) {
521  UInt_t res = 0;
522  const AliESDEvent *eev = dynamic_cast<const AliESDEvent*>(InputEvent());
523  if (eev) {
524  res = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected();
525  } else {
526  const AliAODEvent *aev = dynamic_cast<const AliAODEvent*>(InputEvent());
527  if (aev) {
528  res = ((AliVAODHeader*)aev->GetHeader())->GetOfflineTrigger();
529  }
530  }
531 
532  if ((res & fTriggerMask) == 0) {
533  AliDebug(3, Form("Event rejected due to physics selection. Event trigger mask: %d, trigger mask selection: %d.",
534  res, fTriggerMask));
535  return kFALSE;
536  }
537  }
538 
539  // Vertex selection
540  Double_t externalVertex[3]={0};
541  Double_t inputVertex[3]={0};
542  const AliVVertex *externalVert = fExternalEvent->GetPrimaryVertex();
543  const AliVVertex *inputVert = InputEvent()->GetPrimaryVertex();
544  if (externalVert && inputVert) {
545  externalVert->GetXYZ(externalVertex);
546  inputVert->GetXYZ(inputVertex);
547 
548  if (TMath::Abs(externalVertex[2]) > fZVertexCut) {
549  AliDebug(3, Form("Event rejected due to Z vertex selection. Event Z vertex: %f, Z vertex cut: %f",
550  externalVertex[2], fZVertexCut));
551  return kFALSE;
552  }
553  Double_t dist = TMath::Sqrt((externalVertex[0]-inputVertex[0])*(externalVertex[0]-inputVertex[0])+(externalVertex[1]-inputVertex[1])*(externalVertex[1]-inputVertex[1])+(externalVertex[2]-inputVertex[2])*(externalVertex[2]-inputVertex[2]));
554  if (dist > fMaxVertexDist) {
555  AliDebug(3, Form("Event rejected because the distance between the current and embedded vertices is > %f. "
556  "Current event vertex (%f, %f, %f), embedded event vertex (%f, %f, %f). Distance = %f",
557  fMaxVertexDist, inputVertex[0], inputVertex[1], inputVertex[2], externalVertex[0], externalVertex[1], externalVertex[2], dist));
558  return kFALSE;
559  }
560  }
561 
562  // TODO: Can we do selection based on the contents of the external event input objects?
563  // The previous embedding task could do so by directly accessing the elements.
564  // Certainly can't do jets (say minPt of leading jet) because this has to be embedded before them.
565  // See AliJetEmbeddingFromAODTask::IsAODEventSelected()
566 
567  return kTRUE;
568 }
569 
576 {
577  if (!fChain) return kFALSE;
578 
579  if (!fExternalEvent) {
580  if (fTreeName == "aodTree") {
581  fExternalEvent = new AliAODEvent();
582  }
583  else if (fTreeName == "esdTree") {
584  fExternalEvent = new AliESDEvent();
585  }
586  else {
587  AliError(Form("Tree name %s not recognized!", fTreeName.Data()));
588  return kFALSE;
589  }
590  }
591 
592  fExternalEvent->ReadFromTree(fChain, fTreeName);
593 
594  return kTRUE;
595 }
596 
603 {
604  SetupEmbedding();
605 
606  if (!fCreateHisto) {
607  return;
608  }
609 
610  // Create output list
611  OpenFile(1);
612  fOutput = new AliEmcalList();
613  fOutput->SetOwner();
614 
615  // Create histograms
616  TString histName;
617  TString histTitle;
618 
619  // Cross section
620  histName = "fHistXsection";
621  histTitle = "Pythia Cross Section;p_{T} hard bin; XSection";
622  fHistManager.CreateTProfile(histName, histTitle, fNPtHardBins + 1, -1, fNPtHardBins);
623 
624  // Trials
625  histName = "fHistTrials";
626  histTitle = "Number of Pythia Trials;p_{T} hard bin;Trials";
627  fHistManager.CreateTH1(histName, histTitle, fNPtHardBins + 1, -1, fNPtHardBins);
628 
629  // Pt hard spectra
630  histName = "fHistPtHard";
631  histTitle = "p_{T} Hard Spectra;p_{T} hard;Counts";
632  fHistManager.CreateTH1(histName, histTitle, 500, 0, 1000);
633 
634  // Count of accepted and rejected events
635  histName = "fHistEventCount";
636  histTitle = "fHistEventCount;Result;Count";
637  auto histEventCount = fHistManager.CreateTH1(histName, histTitle, 2, 0, 2);
638  histEventCount->GetXaxis()->SetBinLabel(1,"Accepted");
639  histEventCount->GetXaxis()->SetBinLabel(2,"Total");
640 
641  // Rejected events in embedded event selection
642  histName = "fHistEmbeddingEventsRejected";
643  histTitle = "Number of embedded events rejected by event selection before success;Number of rejected events;Counts";
644  fHistManager.CreateTH1(histName, histTitle, 200, 0, 200);
645 
646  // Add all histograms to output list
647  TIter next(fHistManager.GetListOfHistograms());
648  TObject* obj = 0;
649  while ((obj = next())) {
650  fOutput->Add(obj);
651  }
652 
653  PostData(1, fOutput);
654 }
655 
663 {
664  // Determine which file to start with
666 
667  // Setup TChain
668  fChain = new TChain(fTreeName);
669 
670  // Determine whether AliEn is needed
671  bool requiresAlien = false;
672  for (auto filename : fFilenames)
673  {
674  if (filename.find("alien://") != std::string::npos) {
675  requiresAlien = true;
676  }
677  }
678 
679  if (requiresAlien && !gGrid) {
680  AliInfo("Trying to connect to AliEn ...");
681  TGrid::Connect("alien://");
682  }
683 
684  // Add files for TChain
685  // See: https://stackoverflow.com/a/8533198
686  bool wrapped = false;
687  TString baseFileName("");
688  for (auto filename = fFilenames.begin() + fFilenameIndex; (filename != fFilenames.begin() + fFilenameIndex || !wrapped); filename++)
689  {
690  // Wraps the loop back around to the beginning
691  if (filename == fFilenames.end())
692  {
693  // Explicit check is needed. Otherwise, an offset of 0 would load the 0th entry twice.
694  if (fFilenameIndex == 0) {
695  break;
696  }
697  filename = fFilenames.begin();
698  wrapped = true;
699  }
700 
701  // AccessPathName() cannot handle the "#", so we need to strip it to check that the file exists.
702  baseFileName = filename->c_str();
703  if (baseFileName.Contains(".zip#")) {
704  Ssiz_t pos = baseFileName.Last('#');
705  baseFileName.Remove(pos);
706  }
707 
708  // Ensure that the file is accessible
709  if (gSystem->AccessPathName(baseFileName)) {
710  AliError(Form("File %s does not exist! Skipping!", baseFileName.Data()));
711  // Do not process the file if it is unaccessible, but continue processing
712  continue;
713  }
714 
715  // Add to the Chain
716  fChain->Add(filename->c_str());
717  }
718 
719  // Keep track of the total number of files in the TChain to ensure that we don't start repeating within the chain
720  fMaxNumberOfFiles = fChain->GetListOfFiles()->GetEntries();
721 
722  if (fFilenames.size() > fMaxNumberOfFiles) {
723  AliWarning(TString::Format("Number of input files (%lu) is larger than the number of available files (%i). Some filenames were likely invalid!", fFilenames.size(), fMaxNumberOfFiles));
724  }
725 
726  // Setup input event
727  Bool_t res = InitEvent();
728  if (!res) return kFALSE;
729 
730  return kTRUE;
731 }
732 
739 {
740  if (fInitializedConfiguration == false) {
741  AliFatal("The configuration is not initialized. Check that Initialize() was called!");
742  }
743 
744  // Setup TChain
745  Bool_t res = SetupInputFiles();
746  if (!res) { return; }
747 
748  // Note if getting random event access
750  AliInfo("Random event number access enabled!");
751  }
752 
753  fInitializedEmbedding = kTRUE;
754 }
755 
767 {
768  // Load first entry of the (next) file so that we can query information about it
769  // (it is unaccessible otherwise).
770  // Since fUpperEntry is the total number of entries, loading it will retrieve the
771  // next tree (in the next file) since entries are indexed starting from 0.
772  fChain->GetEntry(fUpperEntry);
773 
774  // Determine tree size and current entry
775  // Set the limits of the new tree
777  // Fine to be += as long as we started at 0
778  fUpperEntry += fChain->GetTree()->GetEntries();
779 
780  // Jump ahead at random if desired
781  // Determines the offset into the tree
783  fOffset = TMath::Nint(gRandom->Rndm()*(fUpperEntry-fLowerEntry))-1;
784  }
785  else {
786  fOffset = 0;
787  }
788 
789  // Sets which entry to start if the try
791 
792  // Keep track of the number of files that we have gone through
793  // To start from 0, we only increment if fLowerEntry > 0
794  if (fLowerEntry > 0) {
795  fFileNumber++;
796  }
797 
798  AliDebug(2, TString::Format("Will start embedding file %i beginning from entry %i (entry %i within the file). NOTE: This file number is not equal to the absolute file number in the file list!", fFileNumber, fCurrentEntry, fCurrentEntry - fLowerEntry));
799  // NOTE: Cannot use this print message, as it is possible that fMaxNumberOfFiles != fFilenames.size() because
800  // invalid filenames may be included in the fFilenames count!
801  //AliDebug(2, TString::Format("Will start embedding file %i as the %ith file beginning from entry %i.", (fFilenameIndex + fFileNumber) % fMaxNumberOfFiles, fFileNumber, fCurrentEntry));
802 
803  // (re)set whether we have wrapped the tree
804  fWrappedAroundTree = false;
805 
806  // Note that the tree in the new file has been initialized
807  fInitializedNewFile = kTRUE;
808 }
809 
816 {
817  if (!fInitializedEmbedding) {
818  AliError("Chain not initialized before running! Setting up now.");
819  SetupEmbedding();
820  }
821 
822  if (!fInitializedNewFile) {
823  InitTree();
824  }
825 
826  Bool_t res = GetNextEntry();
827 
828  if (!res) {
829  AliError("Unable to get the event to embed. Nothing will be embedded.");
830  return;
831  }
832 
833  if (fCreateHisto && fOutput) {
834  PostData(1, fOutput);
835  }
836 }
837 
842 {
843 }
844 
853 {
854  // Get the pointer to the existing analysis manager via the static access method.
855  //==============================================================================
856  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
857  if (!mgr)
858  {
859  ::Error("AddTaskEmcalEmbeddingHelper", "No analysis manager to connect to.");
860  return 0;
861  }
862 
863  // Check the analysis type using the event handlers connected to the analysis manager.
864  //==============================================================================
865  AliVEventHandler* handler = mgr->GetInputEventHandler();
866  if (!handler)
867  {
868  ::Error("AddTaskEmcalEmbeddingHelper", "This task requires an input event handler");
869  return 0;
870  }
871 
872  TString name = "AliAnalysisTaskEmcalEmbeddingHelper";
873 
874  AliAnalysisTaskEmcalEmbeddingHelper * mgrTask = static_cast<AliAnalysisTaskEmcalEmbeddingHelper *>(mgr->GetTask(name.Data()));
875  if (mgrTask) return mgrTask;
876 
877  // Create the task that manages
879 
880  //-------------------------------------------------------
881  // Final settings, pass to manager and set the containers
882  //-------------------------------------------------------
883 
884  mgr->AddTask(embeddingHelper);
885 
886  // Create containers for input/output
887  AliAnalysisDataContainer* cInput = mgr->GetCommonInputContainer();
888 
889  TString outputContainerName(name);
890  outputContainerName += "_histos";
891 
892  AliAnalysisDataContainer * cOutput = mgr->CreateContainer(outputContainerName.Data(),
893  TList::Class(),
894  AliAnalysisManager::kOutputContainer,
895  Form("%s", AliAnalysisManager::GetCommonFileName()));
896 
897  mgr->ConnectInput(embeddingHelper, 0, cInput);
898  mgr->ConnectOutput(embeddingHelper, 1, cOutput);
899 
900  return embeddingHelper;
901 }
902 
908 std::string AliAnalysisTaskEmcalEmbeddingHelper::toString(bool includeFileList) const
909 {
910  std::stringstream tempSS;
911 
912  // Show the correction components
913  tempSS << std::boolalpha;
914  tempSS << GetName() << ": Embedding helper configuration:\n";
915  tempSS << "Create histos: " << fCreateHisto << "\n";
916  tempSS << "Pt Hard Bin: " << fPtHardBin << "\n";
917  tempSS << "Anchor Run: " << fAnchorRun << "\n";
918  tempSS << "File pattern: \"" << fFilePattern << "\"\n";
919  tempSS << "Input filename: \"" << fInputFilename << "\"\n";
920  tempSS << "File list filename: \"" << fFileListFilename << "\"\n";
921  tempSS << "Tree name: " << fTreeName << "\n";
922  tempSS << "Random event number access: " << fRandomEventNumberAccess << "\n";
923  tempSS << "Random file access: " << fRandomFileAccess << "\n";
924  tempSS << "Starting file index: " << fFilenameIndex << "\n";
925  tempSS << "Number of files to embed: " << fFilenames.size() << "\n";
926 
927  std::bitset<32> triggerMask(fTriggerMask);
928  tempSS << "\nEmbedded event settings:\n";
929  tempSS << "Trigger mask (binary): " << triggerMask << "\n";
930  tempSS << "Z vertex cut: " << fZVertexCut << "\n";
931  tempSS << "Max vertex distance: " << fMaxVertexDist << "\n";
932 
933  if (includeFileList) {
934  tempSS << "\nFiles to embed:\n";
935  for (auto filename : fFilenames) {
936  tempSS << "\t" << filename << "\n";
937  }
938  }
939 
940  return tempSS.str();
941 }
942 
950 std::ostream & AliAnalysisTaskEmcalEmbeddingHelper::Print(std::ostream & in) const {
951  in << toString();
952  return in;
953 }
954 
963 std::ostream & operator<<(std::ostream & in, const AliAnalysisTaskEmcalEmbeddingHelper & myTask)
964 {
965  std::ostream & result = myTask.Print(in);
966  return result;
967 }
968 
976 {
977  std::string temp(opt);
978  bool includeFileList = false;
979  if (temp == "FILELIST") {
980  includeFileList = true;
981  }
982  Printf("%s", toString(includeFileList).c_str());
983 }
Bool_t fRandomEventNumberAccess
If true, it will start embedding from a random entry in the file rather than from the first...
Double_t fZVertexCut
Z vertex cut on embedded event.
const char * filename
Definition: TestFCM.C:1
double Double_t
Definition: External.C:58
double fPythiaXSection
! Pythia cross section for the current event (extracted from the pythia header)
Int_t fPtHardBin
ptHard bin for the given pythia production
Int_t fLowerEntry
! First entry of the current tree to be used for embedding
Int_t fAnchorRun
Anchor run for the given pythia production.
TString fFileListFilename
Name of the file list containing paths to files to embed.
Bool_t fRandomFileAccess
If true, it will start embedding from a random file in the input files list.
TSystem * gSystem
Int_t fCurrentEntry
! Current entry in the current tree
TFile * fExternalFile
! External file used for embedding
Int_t fNPtHardBins
Total number of pt hard bins.
TChain * fChain
! External TChain (tree) containing the events available for embedding
Declaration of class AliAnalysisTaskEmcalEmbeddingHelper.
bool fInitializedConfiguration
Notes if the configuration has been initialized.
double fPythiaTrials
! Number of pythia trials for the current event (extracted from the pythia header) ...
AliVHeader * fExternalHeader
! Header of the current external event
AliGenPythiaEventHeader * fPythiaHeader
! Pythia header of the current external event
TRandom * gRandom
TString fInputFilename
Filename of input root files.
Int_t fMaxNumberOfFiles
! Max number of files that are in the TChain
int Int_t
Definition: External.C:63
void CreateTProfile(const char *name, const char *title, int nbinsX, double xmin, double xmax, Option_t *opt="")
Create a new TProfile within the container.
unsigned int UInt_t
Definition: External.C:33
THashList * GetListOfHistograms() const
Get the list of histograms.
Definition: THistManager.h:658
bool fInitializedEmbedding
! Notes where the TChain has been initialized for embedding
std::string toString(bool includeFileList=false) const
Implementation of task to embed external events.
TH1 * CreateTH1(const char *name, const char *title, int nbins, double xmin, double xmax, Option_t *opt="")
Create a new TH1 within the container.
void FillProfile(const char *name, double x, double y, double weight=1.)
Double_t fMaxVertexDist
Max distance between Z vertex of internal and embedded event.
AliVEvent * fExternalEvent
! Current external event available for embedding
void FillTH1(const char *hname, double x, double weight=1., Option_t *opt="")
Fill a 1D histogram within the container.
TString fTreeName
Name of the ESD/AOD tree where the events are to be found.
Int_t fOffset
! Offset from fLowerEntry where the loop over the tree should start
bool fCreateHisto
If true, create QA histograms.
Enhanced TList-derived class that implements correct merging for pt_hard binned production.
Definition: AliEmcalList.h:25
bool fWrappedAroundTree
! Notes whether we have wrapped around the tree, which is important if the offset into the tree is no...
double fPythiaPtHard
! Pt hard of the current event (extracted from the pythia header)
static AliAnalysisTaskEmcalEmbeddingHelper * AddTaskEmcalEmbeddingHelper()
std::ostream & operator<<(std::ostream &in, const AliAnalysisTaskEmcalEmbeddingHelper &myTask)
THistManager fHistManager
! Manages access to all histograms
ClassImp(AliAnalysisTaskCRC) AliAnalysisTaskCRC
bool fInitializedNewFile
! Notes where the entry indices have been initialized for a new tree in the chain ...
static AliAnalysisTaskEmcalEmbeddingHelper * fgInstance
! Global instance of this class
const char Option_t
Definition: External.C:48
AliEmcalList * fOutput
! List which owns the output histograms to be saved
bool Bool_t
Definition: External.C:53
Int_t fUpperEntry
! Last entry of the current tree to be used for embedding
Int_t fFilenameIndex
Index of vector containing paths to files to embed.
std::vector< std::string > fFilenames
Paths to the files to embed.
TString fFilePattern
File pattern to select AliEn files using alien_find.
TList * OpenFile(const char *fname)
Definition: DrawAnaELoss.C:65
Int_t fFileNumber
! File number corresponding to the current tree