1 /**************************************************************************
2 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
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 **************************************************************************/
16 //-----------------------------------------------------------------------------
17 /// \class AliCounterCollection
19 /// generic class to handle a collection of counters
21 /// \author Philippe Pillot
22 //-----------------------------------------------------------------------------
24 #include "AliCounterCollection.h"
29 #include <TObjString.h>
30 #include <TObjArray.h>
31 #include <THnSparse.h>
32 #include <THashList.h>
36 #include <TCollection.h>
38 ClassImp(AliCounterCollection)
40 //-----------------------------------------------------------------------
41 AliCounterCollection::AliCounterCollection(const char* name) :
43 fRubrics(new THashList(10)),
44 fRubricsSize(new TArrayI(10)),
51 //-----------------------------------------------------------------------
52 AliCounterCollection::~AliCounterCollection()
60 //-----------------------------------------------------------------------
61 void AliCounterCollection::Clear(Option_t*)
65 fRubricsSize->Reset();
66 delete fCounters; fCounters = 0x0;
69 //-----------------------------------------------------------------------
70 void AliCounterCollection::AddRubric(TString name, TString listOfKeyWords)
72 /// Add a new rubric with the complete list of related key words separated by "/".
73 /// If the key word "any" is not defined, the overall statistics is
74 /// assumed to be the sum of the statistics under each key word.
77 listOfKeyWords.ToUpper();
79 if (fRubrics->Contains(name.Data())) {
80 AliError(Form("rubric named %s already exist",name.Data()));
84 // add the list of autorized key words
85 TObjArray* rubric = listOfKeyWords.Tokenize("/");
86 CleanListOfStrings(rubric);
87 rubric->SetName(name.Data());
88 Int_t nRubrics = fRubrics->GetSize();
89 rubric->SetUniqueID(nRubrics);
90 fRubrics->AddLast(rubric);
92 // save the number of autorized key words (expand the array if needed)
93 if (nRubrics+1 > fRubricsSize->GetSize()) fRubricsSize->Set(2*fRubricsSize->GetSize());
94 (*fRubricsSize)[nRubrics] = rubric->GetEntriesFast();
97 //-----------------------------------------------------------------------
98 void AliCounterCollection::AddRubric(TString name, Int_t maxNKeyWords)
100 /// Add a new rubric containing at maximum maxNKeyWords key words.
101 /// Key words will be added as the counters get filled until the maximum is reached.
102 /// If the key word "any" is never defined, the overall statistics is
103 /// assumed to be the sum of the statistics under each key word.
107 if (fRubrics->Contains(name.Data())) {
108 AliError(Form("rubric named %s already exist",name.Data()));
112 // create the empty rubric
113 TObjString* rubric = new TObjString(name.Data());
114 Int_t nRubrics = fRubrics->GetSize();
115 rubric->SetUniqueID(nRubrics);
116 fRubrics->AddLast(rubric);
118 // save the maximum number of autorized key words
119 if (nRubrics+1 > fRubricsSize->GetSize()) fRubricsSize->Set(2*fRubricsSize->GetSize());
120 (*fRubricsSize)[nRubrics] = maxNKeyWords;
123 //-----------------------------------------------------------------------
124 void AliCounterCollection::Init()
126 /// Initialize the internal counters from the added rubrics.
128 // create the counters
130 fCounters = new THnSparseT<TArrayI>("hCounters", "hCounters", fRubrics->GetSize(), fRubricsSize->GetArray(), 0x0, 0x0);
133 TObject* rubric = 0x0;
134 TIter nextRubric(fRubrics);
135 while ((rubric = nextRubric())) {
136 TAxis* axis = fCounters->GetAxis((Int_t)rubric->GetUniqueID());
139 axis->SetName(rubric->GetName());
141 // set labels if already known
142 TObjArray* keyWords = dynamic_cast<TObjArray*>(rubric);
144 TObjString* label = 0x0;
146 TIter nextLabel(keyWords);
147 while ((label = static_cast<TObjString*>(nextLabel()))) axis->SetBinLabel(bin++, label->String().Data());
154 //-----------------------------------------------------------------------
155 Int_t AliCounterCollection::GetNActiveBins(Int_t dim)
157 /// return the number of labels in that rubric.
158 THashList* labels = fCounters->GetAxis(dim)->GetLabels();
159 return (labels) ? labels->GetSize() : 0;
162 //-----------------------------------------------------------------------
163 Bool_t AliCounterCollection::ContainsAny(Int_t dim)
165 /// return kTRUE if that rubric contains the keyWord "ANY".
166 THashList* labels = fCounters->GetAxis(dim)->GetLabels();
167 return (labels && labels->Contains("ANY"));
170 //-----------------------------------------------------------------------
171 const Int_t* AliCounterCollection::FindBins(const TString& externalKey, Bool_t allocate, Int_t& nEmptySlots)
173 /// Return the corresponding bins ordered by rubric or 0x0 if externalKey is not valid.
174 /// The externalKey format must be rubric:keyWord/rubric:keyWord/rubric:keyWord/...
175 /// If allocate = kTRUE, new key words are added to the corresponding rubric if possible.
176 /// If a rubric is not filled in, the coresponding slot contain -1 in the array.
177 /// It is the responsability of the user to delete the returned array.
179 // produce an empty array of keys
180 Int_t nRubrics = fRubrics->GetSize();
181 Int_t* bins = new Int_t[nRubrics];
182 for (Int_t i=0; i<nRubrics; i++) bins[i] = -1;
183 nEmptySlots = nRubrics;
184 Bool_t isValid = kTRUE;
186 // get the list of rubric:keyWord pairs
187 TObjArray* rubricKeyPairs = externalKey.Tokenize("/");
189 // loop over each rubric:keyWord pair
190 TObjString* pair = 0x0;
191 TIter next(rubricKeyPairs);
192 while ((pair = static_cast<TObjString*>(next()))) {
194 // get both rubric and associated key word
195 TObjArray* rubricKeyPair = pair->String().Tokenize(":");
197 // check the format of the pair
198 if (rubricKeyPair->GetEntriesFast() != 2) {
199 AliError("invalid key format");
201 delete rubricKeyPair;
205 // get the axis corresponding to that rubric
206 Int_t dim = FindDim(static_cast<TObjString*>(rubricKeyPair->UncheckedAt(0))->String());
209 delete rubricKeyPair;
213 // find the bin corresponding to that key word
214 Int_t bin = FindBin(dim, static_cast<TObjString*>(rubricKeyPair->UncheckedAt(1))->String(), allocate);
217 delete rubricKeyPair;
221 // check if the array of keys already contains something for that rubric
222 if (bins[dim] >= 0) {
223 AliWarning("key already given for that rubric --> ignored");
224 delete rubricKeyPair;
228 // store the corresponding bin for that slot
233 delete rubricKeyPair;
236 // delete the array in case of problem
240 nEmptySlots = nRubrics;
244 delete rubricKeyPairs;
249 //-----------------------------------------------------------------------
250 Int_t AliCounterCollection::FindDim(const TString& rubricName) const
252 /// Return the dimension corresponding to that rubric (or -1 in case of failure).
253 TObject* rubric = fRubrics->FindObject(rubricName.Data());
255 AliError(Form("invalid rubric: %s",rubricName.Data()));
258 return (Int_t) rubric->GetUniqueID();
261 //-----------------------------------------------------------------------
262 Int_t AliCounterCollection::FindBin(Int_t dim, const TString& keyWord, Bool_t allocate)
264 /// Return the bin number corresponding to that key word (or -1 in case of failure).
265 /// If allocate = kTRUE, try to add the key word if possible.
267 TAxis* axis = fCounters->GetAxis(dim);
269 // look for the bin corresponding to keyWord
270 THashList* labels = axis->GetLabels();
271 TObjString* label = (labels) ? static_cast<TObjString*>(labels->FindObject(keyWord.Data())) : 0x0;
272 Int_t bin = (label) ? (Int_t)label->GetUniqueID() : -1;
274 // in case the keyWord does not exist, try to add it if required
275 if (bin<0 && allocate) {
276 Int_t nLabels = (labels) ? labels->GetSize() : 0;
277 if (nLabels < axis->GetNbins()) {
279 axis->SetBinLabel(bin, keyWord.Data());
283 if (bin<0) AliError(Form("invalid key word: %s:%s",axis->GetName(),keyWord.Data()));
288 //-----------------------------------------------------------------------
289 Short_t** AliCounterCollection::DecodeSelection(const TString& selections, const TObjArray& displayedRubrics)
291 /// Tag the selected keywords in each rubric (-1=subtract; 0=discard; 1=add). Format:
292 /// "rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.." (order does not matter).
293 /// It is the responsability of the user to delete the returned array.
295 // produce an empty array of selected keys
296 Int_t nRubrics = fCounters->GetNdimensions();
297 Short_t** selects = new Short_t*[nRubrics];
298 for (Int_t i=0; i<nRubrics; i++) selects[i] = 0x0;
300 // get the list of rubric:LisOfKeyWord pairs
301 TObjArray* rubricKeyPairs = selections.Tokenize("/");
303 // loop over each rubric:keyWord pair
304 TObjString* pair = 0x0;
305 TIter next(rubricKeyPairs);
306 while ((pair = static_cast<TObjString*>(next()))) {
308 // get both rubric and associated list of key words
309 TObjArray* rubricKeyPair = pair->String().Tokenize(":");
311 // check the format of the pair
312 if (rubricKeyPair->GetEntriesFast() != 2) {
313 AliError("invalid key format");
314 delete rubricKeyPair;
315 delete rubricKeyPairs;
316 for (Int_t i=0; i<nRubrics; i++) if (selects[i]) delete[] selects[i];
321 // check wether to select or to discard the keyWords
322 Int_t include = kTRUE;
323 TString ListOfKeyWords(static_cast<TObjString*>(rubricKeyPair->UncheckedAt(1))->String());
324 if (ListOfKeyWords.BeginsWith("ANY-")) {
325 ListOfKeyWords.Remove(0,4);
329 // select the key words
330 const TString& rubric = static_cast<TObjString*>(rubricKeyPair->UncheckedAt(0))->String();
331 if (!Select(include, rubric, ListOfKeyWords, displayedRubrics.Contains(rubric.Data()), selects)) {
332 delete rubricKeyPair;
333 delete rubricKeyPairs;
334 for (Int_t i=0; i<nRubrics; i++) if (selects[i]) delete[] selects[i];
340 delete rubricKeyPair;
344 delete rubricKeyPairs;
346 // complete the selection of other rubrics
347 for (Int_t i=0; i<nRubrics; i++) {
349 // skip already processed rubrics
350 if (selects[i]) continue;
352 // create the list of bins
353 Int_t nBins = GetNActiveBins(i) + 1;
354 selects[i] = new Short_t[nBins];
356 // select all key words or only the key work "ANY"
357 if (ContainsAny(i) && !displayedRubrics.Contains(fCounters->GetAxis(i)->GetName())) {
358 memset(selects[i], 0, sizeof(Short_t) * nBins);
359 selects[i][FindBin(i, "ANY", kFALSE)] = 1;
360 } else for (Int_t j=0; j<nBins; j++) selects[i][j] = 1;
367 //-----------------------------------------------------------------------
368 Bool_t AliCounterCollection::Select(Bool_t include, const TString& rubric, const TString& keywords,
369 Bool_t displayed, Short_t* selectBins[])
371 /// Tag the selected keywords (separated by ',') in that rubric (-1=subtract; 0=discard; 1=add).
373 Int_t dim = FindDim(rubric);
374 if (dim < 0) return kFALSE;
376 if (selectBins[dim]) {
377 AliWarning(Form("selection already made for rubric %s --> ignored",rubric.Data()));
381 // get list of key words to select
382 TObjArray* keys = keywords.Tokenize(",");
383 if (keys->GetEntriesFast() == 0) {
384 AliError(Form("no key word specified for rubric %s",rubric.Data()));
389 // create the list of bins
390 Int_t nBins = GetNActiveBins(dim) + 1;
391 selectBins[dim] = new Short_t[nBins];
393 // select/unselect all bins
394 Bool_t containsAny = ContainsAny(dim);
395 if (include || (containsAny && !displayed)) {
396 memset(selectBins[dim], 0, sizeof(Short_t) * nBins);
397 if (!include) selectBins[dim][FindBin(dim, "ANY", kFALSE)] = 1;
398 } else for (Int_t j=0; j<nBins; j++) selectBins[dim][j] = 1;
400 // select/unselect specific key words
401 TObjString* key = 0x0;
403 while ((key = static_cast<TObjString*>(nextKey()))) {
405 // special case of key word "ANY"
406 if (key->String() == "ANY") {
410 Int_t binAny = FindBin(dim, "ANY", kFALSE);
411 if (include) selectBins[dim][binAny] = 1;
412 else selectBins[dim][binAny] = 0;
416 if (include) for (Int_t j=0; j<nBins; j++) selectBins[dim][j] = 1;
417 else memset(selectBins[dim], 0, sizeof(Short_t) * nBins);
421 } else { // other cases
423 // find the corresponding bin
424 Int_t bin = FindBin(dim, key->String().Data(), kFALSE);
430 // select/unselect it
431 if (include) selectBins[dim][bin] = 1;
432 else if (containsAny && !displayed) selectBins[dim][bin] = -1;
433 else selectBins[dim][bin] = 0;
445 //-----------------------------------------------------------------------
446 void AliCounterCollection::CleanListOfStrings(TObjArray* list)
448 /// Make sure all strings appear only once in this list
450 // remove multiple-occurrence
451 Int_t nEntries = list->GetEntriesFast();
452 for (Int_t i = 0; i < nEntries; i++) {
453 TObjString* entry1 = static_cast<TObjString*>(list->UncheckedAt(i));
454 if (!entry1) continue;
455 for (Int_t j = i+1; j < nEntries; j++) {
456 TObjString* entry2 = static_cast<TObjString*>(list->UncheckedAt(j));
457 if (entry2 && entry2->IsEqual(entry1)) {
458 AliWarning(Form("multiple-occurence of string \"%s\" --> removed",entry2->String().Data()));
464 // remove empty slots
468 //-----------------------------------------------------------------------
469 void AliCounterCollection::Count(TString externalKey, Int_t value)
471 /// Add "value" to the counter referenced by "externalKey".
472 /// The externalKey format must be rubric:keyWord/rubric:keyWord/rubric:keyWord/...
474 if (value < 1) return;
476 AliError("counters are not initialized");
480 externalKey.ToUpper();
482 // convert external to internal key
483 Int_t nEmptySlots = 0;
484 const Int_t* bins = FindBins(externalKey, kTRUE, nEmptySlots);
487 // check for empty slots
488 if (nEmptySlots > 0) {
489 AliError("incomplete key");
494 // increment the corresponding counter
495 fCounters->AddBinContent(bins, (Double_t)value);
501 //-----------------------------------------------------------------------
502 void AliCounterCollection::Print(const Option_t* opt) const
504 /// Print every individual counters if opt=="", else call "Print(TString rubrics=opt, TString selections="")".
506 if (strcmp(opt,"")) {
507 const_cast<AliCounterCollection*>(this)->Print(opt, "");
512 AliError("counters are not initialized");
516 if (fCounters->GetNbins() == 0) {
517 printf("\nall counters are empty\n\n");
521 Int_t nRubrics = fCounters->GetNdimensions();
522 Int_t* bins = new Int_t[nRubrics];
524 // loop over every filled counters
525 for (Long64_t i=0; i<fCounters->GetNbins(); ++i) {
527 // get the content of the bin
528 Int_t value = (Int_t) fCounters->GetBinContent(i, bins);
530 // build the corresponding counter name
532 for (Int_t j=0; j<nRubrics; j++) counter += Form("/%s",fCounters->GetAxis(j)->GetBinLabel(bins[j]));
536 printf("\n%s %d", counter.Data(), value);
544 //-----------------------------------------------------------------------
545 TString AliCounterCollection::GetKeyWords(TString rubric) const
547 /// return the list of key words for the given rubric.
549 TString keyWords = "";
552 AliError("counters are not initialized");
558 // get the dimension corresponding to that rubric
559 Int_t dim = FindDim(rubric);
560 if (dim < 0) return keyWords;
562 // build list of key words
563 TObjString* label = 0x0;
564 TIter nextLabel(fCounters->GetAxis(dim)->GetLabels());
565 while ((label = static_cast<TObjString*>(nextLabel()))) keyWords += Form("%s,",label->String().Data());
566 keyWords.Remove(TString::kTrailing, ',');
571 //-----------------------------------------------------------------------
572 void AliCounterCollection::PrintKeyWords() const
574 /// Print the full list of key words.
577 AliError("counters are not initialized");
582 Int_t nRubrics = fCounters->GetNdimensions();
583 for (Int_t iDim=0; iDim<nRubrics; iDim++) {
584 TAxis* axis = fCounters->GetAxis(iDim);
586 // print rubric's name
587 printf("\n%s:", axis->GetName());
589 // loop over key words
590 Bool_t first = kTRUE;
591 TObjString* label = 0x0;
592 TIter nextLabel(axis->GetLabels());
593 while ((label = static_cast<TObjString*>(nextLabel()))) {
595 //print key word's name
597 printf("%s", label->String().Data());
599 } else printf(",%s", label->String().Data());
606 //-----------------------------------------------------------------------
607 void AliCounterCollection::PrintValue(TString selections)
609 /// Print value of selected counter.
610 /// format of "selections" is rubric:keyWord/rubric:keyWord/rubric:keyWord/...
613 AliError("counters are not initialized");
617 selections.ToUpper();
619 // convert external to internal key
620 Int_t nEmptySlots = 0;
621 const Int_t* selectedBins = FindBins(selections, kFALSE, nEmptySlots);
622 if (!selectedBins) return;
624 // check for empty slots
625 if (nEmptySlots > 0) {
626 AliError("incomplete key");
627 delete[] selectedBins;
632 printf("\n%d\n\n", (Int_t) fCounters->GetBinContent(selectedBins));
635 delete[] selectedBins;
638 //-----------------------------------------------------------------------
639 void AliCounterCollection::Print(TString rubrics, TString selections)
641 /// Print desired rubrics for the given selection:
642 /// - format of "rubrics" is rubric1/rubric2/.. (order matters only for output).
643 /// - format of "selections" is rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.. (order does not matter).
644 /// If "data" contains 1 rubric, the output will be one counter for each element of that rubric.
645 /// If "data" contains 2 rubrics, the output will be an array of counters, rubric1 vs rubric2.
646 /// If "data" contains 3 rubrics, the output will be an array rubric1 vs rubric2 for each element in rubric3.
648 /// Results are integrated over rubrics not specified neither in "rubrics" nor in "selections".
651 AliError("counters are not initialized");
656 selections.ToUpper();
658 // get the rubrics to print
659 TObjArray* rubricsToPrint = rubrics.Tokenize("/");
660 if (rubricsToPrint->GetEntriesFast() == 0) {
661 delete rubricsToPrint;
665 // remove rubrics called twice
666 CleanListOfStrings(rubricsToPrint);
668 // project counters in the rubrics to print according to the selections
669 TObject* hist = Projection(*rubricsToPrint, selections);
671 delete rubricsToPrint;
676 Int_t nRubricsToPrint = rubricsToPrint->GetEntriesFast();
677 if (nRubricsToPrint == 1 && (static_cast<TH1D*>(hist))->GetEntries() > 0)
678 PrintList(static_cast<TH1D*>(hist));
679 else if (nRubricsToPrint == 2 && (static_cast<TH2D*>(hist))->GetEntries() > 0)
680 PrintArray(static_cast<TH2D*>(hist));
681 else if (nRubricsToPrint > 2 && (static_cast<THnSparse*>(hist))->GetEntries() > 0)
682 PrintListOfArrays(static_cast<THnSparse*>(hist));
684 printf("\nselected counters are empty\n\n");
687 delete rubricsToPrint;
691 //-----------------------------------------------------------------------
692 void AliCounterCollection::PrintSum(TString selections)
694 /// Print the overall statistics for the given selection (result is integrated over not specified rubrics):
695 /// - format of "selections" is rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.. (order does not matter).
698 AliError("counters are not initialized");
702 selections.ToUpper();
704 // decode the selections
705 Short_t** select = DecodeSelection(selections, TObjArray());
708 // loop over every filled counters and compute integral
710 Int_t nDims = fCounters->GetNdimensions();
711 Int_t* coord = new Int_t[nDims];
712 for (Long64_t i=0; i<fCounters->GetNbins(); ++i) {
714 // get the content of the counter
715 Double_t value = fCounters->GetBinContent(i, coord);
717 // discard not selected counters and compute the selection factor
718 Int_t selectionFactor = 1;
719 for (Int_t dim = 0; dim < nDims && selectionFactor != 0; dim++) selectionFactor *= select[dim][coord[dim]];
720 if (selectionFactor == 0) continue;
723 sum += selectionFactor * ((Int_t) value);
727 for (Int_t iDim=0; iDim<nDims; iDim++) delete[] select[iDim];
732 printf("\n%d\n\n", sum);
735 //-----------------------------------------------------------------------
736 void AliCounterCollection::PrintList(const TH1D* hist) const
738 /// Print the content of 1D histogram as a list.
740 // set the format to print labels
741 THashList* labels = hist->GetXaxis()->GetLabels();
742 TString format(Form("\n%%%ds %%9d",GetMaxLabelSize(labels)));
744 // print value for each label
745 TObjString* label = 0x0;
746 TIter nextLabel(labels);
747 while ((label = static_cast<TObjString*>(nextLabel()))) {
748 Int_t bin = (Int_t) label->GetUniqueID();
749 printf(format.Data(), label->String().Data(), (Int_t) hist->GetBinContent(bin));
754 //-----------------------------------------------------------------------
755 void AliCounterCollection::PrintArray(const TH2D* hist) const
757 /// Print the content of 2D histogram as an array.
759 // set the format to print labels in X direction
760 THashList* labelsX = hist->GetXaxis()->GetLabels();
761 TString formatX(Form("\n%%%ds ",GetMaxLabelSize(labelsX)));
763 // set the format to print labels in Y direction and values
764 THashList* labelsY = hist->GetYaxis()->GetLabels();
765 Int_t maxLabelSizeY = TMath::Max(9, GetMaxLabelSize(labelsY));
766 TString formatYs(Form("%%%ds ",maxLabelSizeY));
767 TString formatYd(Form("%%%dd ",maxLabelSizeY));
769 // print labels in Y axis
770 printf(formatX.Data()," ");
771 TObjString* labelY = 0x0;
772 TIter nextLabelY(labelsY);
773 while ((labelY = static_cast<TObjString*>(nextLabelY())))
774 printf(formatYs.Data(), labelY->String().Data());
776 // fill array for each label in X axis
777 TObjString* labelX = 0x0;
778 TIter nextLabelX(labelsX);
779 while ((labelX = static_cast<TObjString*>(nextLabelX()))) {
780 Int_t binX = (Int_t) labelX->GetUniqueID();
783 printf(formatX.Data(), labelX->String().Data());
785 // print value for each label in Y axis
787 while ((labelY = static_cast<TObjString*>(nextLabelY()))) {
788 Int_t binY = (Int_t) labelY->GetUniqueID();
789 printf(formatYd.Data(), (Int_t) hist->GetBinContent(binX, binY));
795 //-----------------------------------------------------------------------
796 void AliCounterCollection::PrintListOfArrays(const THnSparse* hist) const
798 /// Print the content of nD histogram as a list of arrays.
800 // set the format to print labels in X direction
801 THashList* labelsX = hist->GetAxis(0)->GetLabels();
802 TString formatX(Form("\n%%%ds ",GetMaxLabelSize(labelsX)));
804 // set the format to print labels in Y direction and values
805 THashList* labelsY = hist->GetAxis(1)->GetLabels();
806 Int_t maxLabelSizeY = TMath::Max(9, GetMaxLabelSize(labelsY));
807 TString formatYs(Form("%%%ds ",maxLabelSizeY));
808 TString formatYd(Form("%%%dd ",maxLabelSizeY));
810 // create a list containing each combination of labels refering the arrays to be printout
812 listOfCombis.SetOwner();
814 // add a first empty combination
815 Int_t nDim = hist->GetNdimensions();
816 listOfCombis.AddLast(new TObjArray(nDim-2));
818 // loop over the nDim-2 other rubrics
819 for (Int_t i=2; i<nDim; i++) {
821 // save the last label of that rubic
822 THashList* labels = hist->GetAxis(i)->GetLabels();
823 TObjString* lastLabel = (labels) ? static_cast<TObjString*>(labels->Last()) : 0x0;
824 if (!lastLabel) return;
826 // prepare iteration over the list of labels
827 TIter nextLabel(labels);
829 // loop over existing combinations
830 TObjLink* lnk = listOfCombis.FirstLink();
833 // get the current combination
834 TObjArray* currentCombi = static_cast<TObjArray*>(lnk->GetObject());
836 // loop over labels in the current rubric
838 TObjString* label = 0x0;
839 while ((label = static_cast<TObjString*>(nextLabel()))) {
841 // stop at the last one
842 if (label == lastLabel) break;
844 // copy the current combination, add the current label to it and add it to the list of combinations
845 TObjArray* combi = new TObjArray(*currentCombi);
846 combi->AddLast(label);
847 listOfCombis.AddBefore(lnk, combi);
850 // add the last label to the current combination
851 currentCombi->AddLast(lastLabel);
858 // create bin coordinates to access individual counters
859 Int_t* bins = new Int_t[nDim];
861 // loop over each combination of labels
862 TObjArray* combi = 0x0;
863 TIter nextCombi(&listOfCombis);
864 while ((combi = static_cast<TObjArray*>(nextCombi()))) {
866 // make the name of the combination and fill the corresponding bin coordinates
867 TString combiName = "/";
868 for (Int_t i=2; i<nDim; i++) {
869 TObjString* label = static_cast<TObjString*>(combi->UncheckedAt(i-2));
870 combiName += Form("%s/",label->String().Data());
871 bins[i] = (Int_t)label->GetUniqueID();
875 Bool_t empty = kTRUE;
876 TObjString* labelX = 0x0;
877 TObjString* labelY = 0x0;
878 TIter nextLabelX(labelsX);
879 TIter nextLabelY(labelsY);
880 while ((labelX = static_cast<TObjString*>(nextLabelX()))) {
881 bins[0] = (Int_t) labelX->GetUniqueID();
883 while ((labelY = static_cast<TObjString*>(nextLabelY()))) {
884 bins[1] = (Int_t) labelY->GetUniqueID();
885 if (((Int_t) hist->GetBinContent(bins)) > 0) {
894 // print the name of the combination of labels refering the incoming array
895 printf("\n%s:\n",combiName.Data());
897 // print labels in Y axis
898 printf(formatX.Data()," ");
900 while ((labelY = static_cast<TObjString*>(nextLabelY())))
901 printf(formatYs.Data(), labelY->String().Data());
903 // fill array for each label in X axis
905 while ((labelX = static_cast<TObjString*>(nextLabelX()))) {
906 bins[0] = (Int_t) labelX->GetUniqueID();
909 printf(formatX.Data(), labelX->String().Data());
911 // print value for each label in Y axis
913 while ((labelY = static_cast<TObjString*>(nextLabelY()))) {
914 bins[1] = (Int_t) labelY->GetUniqueID();
915 printf(formatYd.Data(), (Int_t) hist->GetBinContent(bins));
925 //-----------------------------------------------------------------------
926 Int_t AliCounterCollection::GetMaxLabelSize(THashList* labels) const
928 /// Return the number of characters of the longest label.
929 Int_t maxLabelSize = 0;
930 TObjString* label = 0x0;
931 TIter nextLabel(labels);
932 while ((label = static_cast<TObjString*>(nextLabel())))
933 maxLabelSize = TMath::Max(maxLabelSize, label->String().Length());
937 //-----------------------------------------------------------------------
938 TH1D* AliCounterCollection::Draw(TString rubric, TString selections)
940 /// Draw counters of the rubric "rubric" for the given "selection".
941 /// Format of "selections" is rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.. (order does not matter).
942 /// Results are integrated over rubrics not specified neither in "rubric1" nor in "selections".
943 /// It is the responsability of the user to delete the returned histogram.
946 AliError("counters are not initialized");
951 selections.ToUpper();
953 // fill the rubrics to print
954 TObjArray rubricsToPrint(1);
955 rubricsToPrint.SetOwner();
956 rubricsToPrint.AddLast(new TObjString(rubric.Data()));
958 // project counters in the rubrics to print according to the selections
959 TH1D* hist = static_cast<TH1D*>(Projection(rubricsToPrint, selections));
966 hist->SetStats(kFALSE);
969 TAxis* axis = hist->GetXaxis();
970 THashList* labels = axis->GetLabels();
971 Int_t nLabels = (labels) ? labels->GetSize() : 1;
972 axis->SetRange(1,nLabels);
973 axis->SetNdivisions(1,kFALSE);
974 axis->SetTitle(rubric.Data());
977 hist->GetYaxis()->SetTitle("Counts");
983 //-----------------------------------------------------------------------
984 TH2D* AliCounterCollection::Draw(TString rubric1, TString rubric2, TString selections)
986 /// Draw counters of the "rubric1" vs "rubric2" for the given "selection".
987 /// Format of "selections" is rubric:[any-]keyWord,keyWord,../rubric:[any-]keyWord,.. (order does not matter).
988 /// Results are integrated over rubrics not specified neither in "rubric1", "rubric2" nor in "selections".
989 /// It is the responsability of the user to delete the returned histogram.
992 AliError("counters are not initialized");
998 selections.ToUpper();
1000 // fill the rubrics to print
1001 TObjArray rubricsToPrint(2);
1002 rubricsToPrint.SetOwner();
1003 rubricsToPrint.AddLast(new TObjString(rubric2.Data()));
1004 rubricsToPrint.AddLast(new TObjString(rubric1.Data()));
1006 // project counters in the rubrics to print according to the selections
1007 TH2D* hist = static_cast<TH2D*>(Projection(rubricsToPrint, selections));
1014 hist->SetStats(kFALSE);
1017 TAxis* axisX = hist->GetXaxis();
1018 THashList* labelsX = axisX->GetLabels();
1019 Int_t nLabelsX = (labelsX) ? labelsX->GetSize() : 1;
1020 axisX->SetRange(1,nLabelsX);
1021 axisX->SetNdivisions(1,kFALSE);
1022 axisX->SetTitle(rubric2.Data());
1025 TAxis* axisY = hist->GetYaxis();
1026 THashList* labelsY = axisY->GetLabels();
1027 Int_t nLabelsY = (labelsY) ? labelsY->GetSize() : 1;
1028 axisY->SetRange(1,nLabelsY);
1029 axisY->SetNdivisions(1,kFALSE);
1030 axisY->SetTitle(rubric1.Data());
1036 //-----------------------------------------------------------------------
1037 TObject* AliCounterCollection::Projection(const TObjArray& data, const TString& selections)
1039 /// Return desired "data" for the given "selection" stored in a new histogram or 0x0 in case of failure.
1040 /// The type of the histogram (TH1D, TH2D or THnSparse) depend on the number of data.
1041 /// It is the responsability of the user to delete the returned histogram.
1043 // decode the selections
1044 Short_t** select = DecodeSelection(selections, data);
1045 if (!select) return 0x0;
1047 // define name and dimensions of projection histo
1048 TString name(fCounters->GetName());
1049 Int_t nDims = fCounters->GetNdimensions();
1050 Int_t nTargetDims = data.GetEntriesFast();
1051 TArrayI targetDims(nTargetDims);
1052 TArrayI nNewBins(nTargetDims);
1053 TArrayI* OldToNewCoord = new TArrayI[nTargetDims];
1054 for (Int_t i=0; i<nTargetDims; i++) {
1057 name += Form("_%s",static_cast<TObjString*>(data.UncheckedAt(i))->String().Data());
1060 targetDims[i] = FindDim(static_cast<TObjString*>(data.UncheckedAt(i))->String());
1062 // set number of selected bins in the target dims and make the correspondence between old and new coordinates
1064 if (targetDims[i] > -1) {
1065 Int_t nBins = GetNActiveBins(targetDims[i]) + 1;
1066 OldToNewCoord[i].Set(nBins);
1067 for (Int_t j=1; j<nBins; j++) if (select[targetDims[i]][j] > 0) OldToNewCoord[i][j] = ++nNewBins[i];
1070 // clean memory and return 0x0 in case of problem
1071 if (nNewBins[i] == 0) {
1072 for (Int_t iDim=0; iDim<nDims; iDim++) delete[] select[iDim];
1074 delete[] OldToNewCoord;
1080 // define title of projection histo
1081 TString title = "Selections: ";
1082 TString selectionString(selections);
1083 selectionString.Remove(TString::kBoth, '/');
1084 if (selectionString.Length() > 0) title += Form("%s/", selectionString.Data());
1086 TIter nextRubric(fRubrics);
1087 while ((rub = nextRubric())) {
1088 if (selectionString.Contains(Form("%s:",rub->GetName()))) continue;
1089 if (data.Contains(rub->GetName())) continue;
1090 title += Form("%s:ANY/", rub->GetName());
1092 title.ReplaceAll("/", " ");
1094 // Create new histograms
1096 if (nTargetDims == 1) hist = new TH1D(name.Data(), title.Data(), nNewBins[0], 0., 1.);
1097 else if (nTargetDims == 2) hist = new TH2D(name.Data(), title.Data(), nNewBins[0], 0., 1., nNewBins[1], 0., 1.);
1098 else hist = new THnSparseT<TArrayI>(name.Data(), title.Data(), nTargetDims, nNewBins.GetArray(), 0x0, 0x0);
1100 // Set new axis labels
1102 if (nTargetDims < 3) {
1105 TIter nextLabelX(fCounters->GetAxis(targetDims[0])->GetLabels());
1106 while ((label = static_cast<TObjString*>(nextLabelX()))) {
1107 if (select[targetDims[0]][label->GetUniqueID()] > 0) {
1108 static_cast<TH1*>(hist)->GetXaxis()->SetBinLabel(OldToNewCoord[0][label->GetUniqueID()], label->String().Data());
1113 if (nTargetDims == 2) {
1114 TIter nextLabelY(fCounters->GetAxis(targetDims[1])->GetLabels());
1115 while ((label = static_cast<TObjString*>(nextLabelY()))) {
1116 if (select[targetDims[1]][label->GetUniqueID()] > 0) {
1117 static_cast<TH1*>(hist)->GetYaxis()->SetBinLabel(OldToNewCoord[1][label->GetUniqueID()], label->String().Data());
1125 for (Int_t i=0; i<nTargetDims; i++) {
1126 TIter nextLabel(fCounters->GetAxis(targetDims[i])->GetLabels());
1127 while ((label = static_cast<TObjString*>(nextLabel()))) {
1128 if (select[targetDims[i]][label->GetUniqueID()] > 0) {
1129 static_cast<THnSparse*>(hist)->GetAxis(i)->SetBinLabel(OldToNewCoord[i][label->GetUniqueID()], label->String().Data());
1136 // loop over every filled counters
1137 Int_t* coord = new Int_t[nDims];
1138 Int_t* newCoord = new Int_t[nTargetDims];
1140 for (Long64_t i=0; i<fCounters->GetNbins(); ++i) {
1142 // get the content of the counter
1143 Double_t value = fCounters->GetBinContent(i, coord);
1145 // discard not selected counters and compute the selection factor
1146 Int_t selectionFactor = 1;
1147 for (Int_t dim = 0; dim < nDims && selectionFactor != 0; dim++) selectionFactor *= select[dim][coord[dim]];
1148 if (selectionFactor == 0) continue;
1150 // find new coordinates in the projection histo
1151 for (Int_t d = 0; d < nTargetDims; ++d) newCoord[d] = OldToNewCoord[d][coord[targetDims[d]]];
1153 // fill projection histo
1154 if (nTargetDims < 3) {
1155 Int_t linBin = (nTargetDims == 1) ? newCoord[0] : static_cast<TH1*>(hist)->GetBin(newCoord[0], newCoord[1]);
1156 static_cast<TH1*>(hist)->AddBinContent(linBin, selectionFactor*value);
1157 } else static_cast<THnSparse*>(hist)->AddBinContent(newCoord, selectionFactor*value);
1162 // update the number of entries
1163 if (nTargetDims < 3) static_cast<TH1*>(hist)->SetEntries(nEntries);
1164 else static_cast<THnSparse*>(hist)->SetEntries(nEntries);
1167 for (Int_t iDim=0; iDim<nDims; iDim++) delete[] select[iDim];
1171 delete[] OldToNewCoord;
1176 //-----------------------------------------------------------------------
1177 Int_t* AliCounterCollection::CheckConsistency(const AliCounterCollection* c)
1179 /// Consistency check of the two counter collections. To be consistent, both counters
1180 /// must have the same rubrics with the same list of authorized key words if any.
1181 /// Return the correspondence between the local rubric ordering and the one of the other counter,
1182 /// or 0x0 in case of problem. It is the responsability of the user to delete the returned array.
1184 if (!fCounters || !c->fCounters) {
1185 AliError("counters are not initialized");
1189 // check if the number of rubrics is the same
1190 Int_t nRubrics = fRubrics->GetSize();
1191 if (c->fRubrics->GetSize() != nRubrics) {
1192 AliError("both counters do not contain the same number of rubrics");
1196 Int_t* otherDims = new Int_t[nRubrics];
1198 // loop over local rubrics
1199 TObject* rubric1 = 0x0;
1200 TIter nextRubric(fRubrics);
1201 while ((rubric1 = nextRubric())) {
1203 // find that rubric in the other counter
1204 TObject* rubric2 = c->fRubrics->FindObject(rubric1->GetName());
1206 AliError(Form("the other counter does not contain the rubric %s", rubric1->GetName()));
1211 // check the list of authorized key words if any
1212 TObjArray* keyWords1 = dynamic_cast<TObjArray*>(rubric1);
1213 TObjArray* keyWords2 = dynamic_cast<TObjArray*>(rubric2);
1214 if (keyWords1 && keyWords2) {
1216 // check if the number of key words is the same
1217 if (keyWords1->GetEntriesFast() != keyWords2->GetEntriesFast()) {
1218 AliError("that rubric does not contain the same number of authorized key words in both counters");
1223 // loop over local key words
1224 TObjString* keyWord = 0x0;
1225 TIter nextKeyWord(keyWords1);
1226 while ((keyWord = static_cast<TObjString*>(nextKeyWord()))) {
1228 // find that key word in the corresponding rubric of the other counter
1229 if (!keyWords2->FindObject(keyWord->String().Data())) {
1230 AliError(Form("rubric %s does not contain the key word %s in the other counter", rubric1->GetName(), keyWord->String().Data()));
1237 } else if (keyWords1 || keyWords2) {
1239 // that rubric has not been initialized the same way in both counter
1241 AliError(Form("rubric %s of the other counter does not contain a list of authorized key words while this does", rubric1->GetName()));
1243 AliError(Form("rubric %s of this counter does not contain a list of authorized key words while the other does", rubric1->GetName()));
1250 // save the correspondence of rubric IDs in both counters
1251 otherDims[rubric1->GetUniqueID()] = rubric2->GetUniqueID();
1258 //-----------------------------------------------------------------------
1259 void AliCounterCollection::Add(const AliCounterCollection* counter)
1261 /// Add the given AliCounterCollections to this. They must have the
1262 /// same rubrics with the same list of authorized key words if any.
1264 // check the consistency between the other counter and this and get the correspondences between rubric IDs.
1265 Int_t* otherDims = CheckConsistency(counter);
1266 if (!otherDims) return;
1268 Int_t nRubrics = fCounters->GetNdimensions();
1269 Int_t* thisBins = new Int_t[nRubrics];
1270 Int_t* otherBins = new Int_t[nRubrics];
1272 // loop over every filled bins inside the other counter
1273 for (Long64_t i = 0; i < counter->fCounters->GetNbins(); i++) {
1275 // get the content of the bin
1276 Double_t value = counter->fCounters->GetBinContent(i, otherBins);
1278 // convert "other" bin coordinates to "this" bin coordinates
1280 for (Int_t dim = 0; dim < nRubrics; dim++) {
1281 TString label = counter->fCounters->GetAxis(otherDims[dim])->GetBinLabel(otherBins[otherDims[dim]]);
1282 thisBins[dim] = FindBin(dim, label, kTRUE);
1283 if (thisBins[dim] < 0) {
1284 AliError("this counter is full, unable to add that key word");
1291 // increment the corresponding local counter
1292 fCounters->AddBinContent(thisBins, value);
1301 //-----------------------------------------------------------------------
1302 Long64_t AliCounterCollection::Merge(TCollection* list)
1304 /// Merge this with a list of AliCounterCollections. All AliCounterCollections provided
1305 /// must have the same rubrics with the same list of authorized key words if any.
1307 if (!list || !fCounters) return 0;
1308 if (list->IsEmpty()) return (Long64_t)fCounters->GetEntries();
1311 const TObject* obj = 0x0;
1312 while ((obj = next())) {
1314 // check that "obj" is an object of the class AliCounterCollection
1315 const AliCounterCollection* counter = dynamic_cast<const AliCounterCollection*>(obj);
1317 AliError(Form("object named %s is not AliCounterCollection! Skipping it.", counter->GetName()));
1321 // merge counter to this one
1326 return (Long64_t)fCounters->GetEntries();
1329 //-----------------------------------------------------------------------
1330 void AliCounterCollection::Sort(Option_t* opt, Bool_t asInt)
1332 /// Sort rubrics defined without a list of authorized key words or all rubrics if opt=="all".
1333 /// If asInt=kTRUE, key words are ordered as interger instead of alphabetically.
1336 AliError("counters are not initialized");
1340 Bool_t all = (!strcasecmp(opt, "all"));
1342 Bool_t somethingToSort = kFALSE;
1343 Int_t nRubrics = fRubrics->GetSize();
1344 Bool_t* rubricsToSort = new Bool_t[nRubrics];
1345 memset(rubricsToSort, kFALSE, sizeof(Bool_t) * nRubrics);
1347 // choose rubrics to sort
1348 TObject* rubric = 0x0;
1349 TIter nextRubric(fRubrics);
1350 while ((rubric = nextRubric())) {
1352 if (all || dynamic_cast<TObjString*>(rubric)) {
1354 // check if something to sort
1355 THashList* labels = fCounters->GetAxis((Int_t)rubric->GetUniqueID())->GetLabels();
1356 if (!labels || labels->GetSize() < 2) continue;
1358 // select that rubric
1359 rubricsToSort[(Int_t)rubric->GetUniqueID()] = kTRUE;
1360 somethingToSort = kTRUE;
1366 // sort selected rubrics if any
1367 if (somethingToSort) Sort(rubricsToSort, asInt);
1370 delete[] rubricsToSort;
1373 //-----------------------------------------------------------------------
1374 void AliCounterCollection::SortRubric(TString rubric, Bool_t asInt)
1376 /// Sort only that rubric. If asInt=kTRUE, key words are ordered as interger instead of alphabetically.
1379 AliError("counters are not initialized");
1385 // find the rubric to sort
1386 Int_t dim = FindDim(rubric);
1387 if (dim < 0) return;
1389 // check if something to sort
1390 THashList* labels = fCounters->GetAxis(dim)->GetLabels();
1391 if (!labels || labels->GetSize() < 2) return;
1393 // select that rubric
1394 Int_t nRubrics = fRubrics->GetSize();
1395 Bool_t* rubricsToSort = new Bool_t[nRubrics];
1396 memset(rubricsToSort, kFALSE, sizeof(Bool_t) * nRubrics);
1397 rubricsToSort[dim] = kTRUE;
1400 Sort(rubricsToSort, asInt);
1403 delete[] rubricsToSort;
1406 //-----------------------------------------------------------------------
1407 void AliCounterCollection::Sort(const Bool_t* rubricsToSort, Bool_t asInt)
1409 /// Sort labels (alphabetically or as integer) in each rubric flagged in "rubricsToSort".
1411 // create a new counter
1412 THnSparse* oldCounters = fCounters;
1413 Int_t nRubrics = fRubrics->GetSize();
1414 fCounters = new THnSparseT<TArrayI>("hCounters", "hCounters", nRubrics, fRubricsSize->GetArray(), 0x0, 0x0);
1415 Int_t** newBins = new Int_t*[nRubrics];
1417 // define the new axes
1418 for (Int_t i=0; i<nRubrics; i++) {
1419 TAxis* oldAxis = oldCounters->GetAxis(i);
1420 TAxis* newAxis = fCounters->GetAxis(i);
1422 // set the name of the new axis
1423 newAxis->SetName(oldAxis->GetName());
1426 THashList* oldLabels = oldAxis->GetLabels();
1427 if (!oldLabels) continue;
1429 // sort them if required
1430 if (rubricsToSort[i]) {
1431 if (asInt) { oldLabels = SortAsInt(oldLabels); }
1432 else { oldLabels->Sort(); }
1435 // set labels in the new axis and save the correspondence between new and old bins
1436 newBins[i] = new Int_t[oldLabels->GetSize()+1];
1437 TObjString* label = 0x0;
1439 TIter nextLabel(oldLabels);
1440 while ((label = static_cast<TObjString*>(nextLabel()))) {
1441 newAxis->SetBinLabel(bin, label->String().Data());
1442 newBins[i][(Int_t)label->GetUniqueID()] = bin;
1447 if (rubricsToSort[i] && asInt) delete oldLabels;
1450 // fill the new counters
1451 Int_t* oldCoor = new Int_t[nRubrics];
1452 Int_t* newCoor = new Int_t[nRubrics];
1453 for (Long64_t i = 0; i < oldCounters->GetNbins(); i++) {
1454 Double_t value = oldCounters->GetBinContent(i, oldCoor);
1455 for (Int_t dim = 0; dim < nRubrics; dim++) newCoor[dim] = newBins[dim][oldCoor[dim]];
1456 fCounters->AddBinContent(newCoor, value);
1460 for (Int_t i=0; i<nRubrics; i++) delete[] newBins[i];
1467 //-----------------------------------------------------------------------
1468 THashList* AliCounterCollection::SortAsInt(const THashList* labels)
1470 /// Return a list (not owner) of labels sorted assuming they are integers.
1471 /// It is the responsability of user to delete the returned list.
1473 THashList* sortedLabels = new THashList(labels->GetSize());
1474 TIter nextSortedLabel(sortedLabels);
1477 TObjString* label = 0x0;
1478 TIter nextLabel(labels);
1479 while ((label = static_cast<TObjString*>(nextLabel()))) {
1481 // find where to add it
1482 TObjString* sortedLabel = 0x0;
1483 nextSortedLabel.Reset();
1484 while ((sortedLabel = static_cast<TObjString*>(nextSortedLabel())) &&
1485 (sortedLabel->String().Atoi() <= label->String().Atoi())) {}
1488 if (sortedLabel) sortedLabels->AddBefore(sortedLabel, label);
1489 else sortedLabels->AddLast(label);
1492 return sortedLabels;