forked from alisw/AliRoot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AliTreePlayer.cxx
1572 lines (1499 loc) · 63 KB
/
AliTreePlayer.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "TStatToolkit.h"
#include "Riostream.h"
#include <iostream>
#include "TSystem.h"
#include "TNamed.h"
#include "TFile.h"
#include "TTree.h"
#include "TPRegexp.h"
#include "TFriendElement.h"
#include "AliExternalInfo.h"
#include "TTreeFormula.h"
#include "TTreeFormulaManager.h"
#include "AliTreePlayer.h"
#include "TEntryList.h"
#include "THn.h"
#include "TLegend.h"
#include "TBufferJSON.h"
#include <sstream>
#include <bitset>
#include "TTimeStamp.h"
using namespace std;
ClassImp(AliTreePlayer)
ClassImp(AliTreeFormulaF)
/// Default constructor
AliTreeFormulaF::AliTreeFormulaF() : TTreeFormula(), fTextArray(NULL), fFormatArray(NULL), fFormulaArray(NULL),fValue(""),fDebug(0) {
}
///
/// \param name
/// \param formula
/// \param tree
AliTreeFormulaF::AliTreeFormulaF(const char *name, const char *formula, TTree *tree, Int_t debug):
TTreeFormula(), fTextArray(NULL), fFormatArray(NULL), fFormulaArray(NULL), fValue(""), fDebug(debug) {
SetName(name);
SetTitle(formula);
SetTree(tree);
Compile(formula);
SetBit(kIsCharacter);
}
AliTreeFormulaF::~AliTreeFormulaF() {
/// TODO - check if not memory leak
delete fTextArray;
delete fFormulaArray;
delete fFormatArray;
}
/// Compile Formatted expression
/// \param expression
/// \return
/// TODO - Error handling - invalidate expression in case of the compilation error
Int_t AliTreeFormulaF::Compile(const char *expression) {
TTree *tree = GetTree();
TString fquery = expression;
//
// 1. GetList of %format{variables} to query
// format: TStringf
// variable: TTreeFormula
// 3. GetFormatted string
//
Int_t sLength = fquery.Length(); // original format string
Int_t iVar = 0;
Int_t varBegin = -1;
fFormulaArray = new TObjArray;
fFormatArray = new TObjArray;
fTextArray = new TObjArray;
Int_t nVars = 0;
Int_t lastI = 0;
Int_t iChar = 0;
for (iChar = 0; iChar < fquery.Length(); iChar++) {
if (fquery[iChar] != '{') continue;
Int_t delta0 = 1, deltaf = 0;
for (delta0 = 1; delta0 + iChar < fquery.Length(); delta0++) if (fquery[iChar + delta0] == '}') break;
for (deltaf = -1; deltaf + iChar >= 0; deltaf--) if (fquery[iChar + deltaf] == '%') break;
TString stext(fquery(lastI, iChar + deltaf - lastI));
TString sformat(fquery(iChar + deltaf + 1, -(deltaf + 1)));
TString sformula(fquery(iChar + 1, delta0 - 1));
if (fDebug&4) { ///TODO - add AliDebug
printf("%d\t%d\t%d\n", iChar, deltaf, delta0);
printf("%d\t%s\t%s\t%s\n", nVars, stext.Data(), sformat.Data(), sformula.Data());
}
fFormatArray->AddAtAndExpand(new TObjString(sformat.Data()), nVars);
fTextArray->AddAtAndExpand(new TObjString(stext.Data()), nVars);
fFormulaArray->AddAtAndExpand(new TTreeFormula(sformula.Data(), sformula.Data(), tree), nVars);
nVars++;
lastI = iChar + delta0 + 1;
}
TString stext(fquery(lastI, fquery.Length() - lastI));
fTextArray->AddAtAndExpand(new TObjString(stext.Data()), nVars);
}
///
/// \param mode
/// \return
char *AliTreeFormulaF::PrintValue(Int_t mode) const {
PrintValue(mode, 0, "");
}
/// Overwrite TTreeFormula PrintValue
/// \param mode
/// \param instance
/// \param decform
/// \return
/// TODO - proper treatment of the 64bits/32 bits integer
/// TODO - speed up evaluation caching information (e.g format type )
/// - get rid of the root formatting string and use sprintf formatting
/// - e.g using t
char *AliTreeFormulaF::PrintValue(Int_t mode, Int_t instance, const char *decform) const {
std::stringstream stream;
Int_t nVars = fFormulaArray->GetEntries();
const char *format=NULL;
for (Int_t iVar = 0; iVar <= nVars; iVar++) {
stream << fTextArray->At(iVar)->GetName();
if (fDebug&2) cout<<"T"<<iVar<<"\t\t"<<fTextArray->At(iVar)->GetName()<<endl;
if (fDebug&4) cout<<"F"<<iVar<<"\t\t"<<stream.str().data()<<endl;
if (iVar < nVars) {
TTreeFormula *treeFormula = (TTreeFormula *) fFormulaArray->At(iVar);
Bool_t isHex=TString(fFormatArray->At(iVar)->GetName()).Contains("x") || TString(fFormatArray->At(iVar)->GetName()).Contains("X");
if (isHex) { // TODO check 64bits/32 bits
char buffer[64];
Int_t value=treeFormula->EvalInstance();
//sprintf(format,"%s",fFormatArray->At(iVar)->GetName());
sprintf(buffer,"%X",(Int_t)value);
stream<<buffer;
continue;
}
if ((fFormatArray->At(iVar)->GetName()[0]=='b')) { //TODO parse number of bits
Long64_t value=treeFormula->EvalInstance();
bitset<32> b(value);
stream<<b.to_string();
continue;
}
if ((fFormatArray->At(iVar)->GetName()[0]=='t')) { //TODO use formats
Long64_t value=treeFormula->EvalInstance64();
TTimeStamp stamp(value);
stream<<stamp.AsString("s");
continue;
}
TString value=treeFormula->PrintValue(0, instance, fFormatArray->At(iVar)->GetName());
stream << value.Data();
if (fDebug&&1) cout<<"F"<<iVar<<"\t\t"<<value.Data()<<"\t"<<fFormatArray->At(iVar)->GetName()<<endl;
}
}
//const_cast<AliTreeFormulaF*>(this)->fValue=TString(stream.str().data()); /// TODO check compliation of mutable in old c++
fValue=stream.str().data();
return (char *) fValue.Data();
}
///
void AliTreeFormulaF::UpdateFormulaLeaves(){
if (fFormulaArray==NULL) return;
return;
Int_t nVars = fFormulaArray->GetEntries();
for (Int_t iVar = 0; iVar <= nVars; iVar++) {
TTreeFormula *treeFormula = (TTreeFormula *) fFormulaArray->At(iVar);
treeFormula->UpdateFormulaLeaves();
}
}
/// Dummy AliTreePlayerConstructor
/// \param name
/// \param title
AliTreePlayer::AliTreePlayer(const char *name, const char *title)
:TNamed(name, title)
{
//
//
}
/// Selected metadata fil filing query
/// retun TObjArray of selected metadata
/// \param tree
/// \param query
/// \param verbose
/// \return TObjArray of selected metadata
/*!
Example usage:
\code
query="[AxisTitle]"; // only metadata with metadata axis existing
query="[class]"; // only metadata with metadata class existing
query="[class==\"Base&&Log&&Stat\"]"; // metadata class contains
//
AliTreePlayer::selectMetadata(treeLogbook, "[class==\"Logbook&&(Stat||Base)\"]",0)->Print();
AliTreePlayer::selectMetadata(testTree, "[Axis==\"counts\"]",0)->Print();
\endcode
*/
TObjArray * AliTreePlayer::selectMetadata(TTree * tree, TString query, Int_t verbose, TString *idList){
/*
query - case sensitive matching is done using Contains method (e.g N(Axis)<=N(xis) )
- WILL be case insesitive
*/
//
// 1. Parse query and map query to TFormula selection
//
TObjArray *queryArray=query.Tokenize("[=]");
TObjArray *varArray=0;
TVectorD vecParam;
TFormula *pFormula=0;
if (queryArray->GetEntries()>1) {
TString stringFormula="";
varArray = TString(queryArray->At(1)->GetName()).Tokenize("\"&|!()[]+-/"); //find variable list
vecParam.ResizeTo(varArray->GetEntriesFast());
stringFormula=queryArray->At(1)->GetName();
stringFormula.ReplaceAll("\"","");
for (Int_t ivar=0; ivar<varArray->GetEntriesFast(); ivar++){
stringFormula.ReplaceAll(varArray->At(ivar)->GetName(),TString::Format("x[%d]",ivar).Data()); // Logic should be improved - to match only "full strings"
vecParam[ivar]=1;
}
pFormula= new TFormula("printMetadataFromula",stringFormula.Data());
if (verbose&0x2) pFormula->Print();
}
//
if (queryArray->GetEntriesFast()<=0 ){
return 0;
}else{
if (queryArray->GetEntriesFast()>2) {
return 0;
}
}
//
// 2.) Find selected data and add the to the list
//
TObjArray * metaData = (TObjArray*)tree->GetUserInfo()->FindObject("metaTable");
Int_t entries = metaData->GetEntries();
TObjArray *selected = new TObjArray(entries);
for (Int_t ientry=0;ientry<entries; ientry++){
TString index=metaData->At(ientry)->GetName();
if (strstr(metaData->At(ientry)->GetName(),queryArray->At(0)->GetName())==NULL) continue;
Bool_t isSelected=kTRUE;
if (queryArray->GetEntriesFast()>1){
for (Int_t ipar=0; ipar< vecParam.GetNrows(); ipar++){
vecParam[ipar]=strstr(metaData->At(ientry)->GetTitle(),varArray->At(ipar)->GetName())!=NULL;
}
isSelected=pFormula->EvalPar(vecParam.GetMatrixArray());
if (verbose&0x2){
vecParam.GetMatrixArray();
}
}
if (isSelected){
selected->AddLast(metaData->At(ientry));
if (idList){
TString id=metaData->At(ientry)->GetName();
id.Remove(id.Last('.'),id.Length());
if (id.Length()>0) {
(*idList) += id;
(*idList) +=":";
}
}
if (verbose&0x1){
printf("%s:%s:%d\n",metaData->At(ientry)->GetName(),metaData->At(ientry)->GetTitle(),isSelected);
}
}
}
if (idList!=NULL){
delete selected;
return NULL;
}
return selected;
}
/// Find all branches containing "Data string" and having class base
/// search follow only branches - does not not enter into classes
/// == - for exact match
/// : - for contain
/// Implemented using TFormula interpreter:
/// - TODO - not case sensitive (should be part of unit test)
/// \param tree - input tree
/// \param query - query string
/// \param verbose - verbosity
/// \return
/*!
### Implementation using TFormula
\code
TString query="([.name==Data])&&([.class==base]||[.class==Data])";
==>
TFormula (x[0])&&(x[1]||x[2])
\endcode
### Example cases :
\code
AliTreePlayer::selectTreeInfo(treeTPC, "([.name:mean] && [.name:MIP])",0)->Print();
AliTreePlayer:: selectTreeInfo(treeLogbook, "([.name:ata] && [.AxisTitle:size])",0)->Print();
In case of problems unit test in separate file
-- AliTreePlayerTest.C::testselectTreeInfo()
\endcode
*/
TObjArray * AliTreePlayer::selectTreeInfo(TTree* tree, TString query,Int_t verbose){
// 1.) Make a TFormula replacing logical operands with values
TObjArray *queryArray=query.Tokenize("&|()!");
Int_t formulaEntries=queryArray->GetEntries();
for (Int_t i=0;i<formulaEntries; i++){
if (TString(queryArray->At(i)->GetName()).ReplaceAll(" ","").Length()<=0) queryArray->RemoveAt(i);
}
queryArray->Compress();
formulaEntries=queryArray->GetEntries();
if (formulaEntries<=0){
::Error("selectTreeInfo","Empty or wrong selection %s", query.Data());
return 0;
}
TString stringFormula=query;
TVectorD formValue(formulaEntries); // boolen or weight value
TVectorF formType(formulaEntries); // type of formula - name or metadata
TVectorF formExact(formulaEntries); // type of formula - exact or contain
TObjArray formMatch(formulaEntries); // string to match
TObjArray formMatchType(formulaEntries); // type to match
for (Int_t ivar=0; ivar<formulaEntries; ivar++){
TString formName=queryArray->At(ivar)->GetName();
stringFormula.ReplaceAll(queryArray->At(ivar)->GetName(),TString::Format("x[%d]",ivar).Data()); // Logic should be improved - to match only "full strings"
formName.ReplaceAll(" ","");
formName.ReplaceAll("\t","");
TObjArray *tokenArray=formName.Tokenize("[=:]");
if (tokenArray->GetEntries()<2){
::Error("selectTreeInfo","Wrong subformula %s",formName.Data());
::Error("selectTreeInfo","Full formula was %s",query.Data());
tokenArray->Print();
queryArray->Print();
delete tokenArray;
delete queryArray;
return 0;
}
formMatch[ivar]=tokenArray->At(1);
formMatchType[ivar]=tokenArray->At(0);
TString queryType(tokenArray->At(0)->GetName());
queryType.ToLower();
formType[ivar]=1;
if (queryType.Contains(".name",TString::kIgnoreCase)){
formType[ivar]=0;
}
if (formName.Contains(":")){
formExact[ivar]=0;
}else{
formExact[ivar]=1;
}
}
//
TFormula *pFormula= new TFormula("printMetadataFormula",stringFormula.Data());
if (verbose&0x4){
::Info("selectTreeInfo","Formula:");
pFormula->Print();
::Info("selectTreeInfo","Query array:");
queryArray->Print();
::Info("selectTreeInfo","To match array:");
formMatch.Print();
::Info("selectTreeInfo","Exact type:");
formExact.Print();
}
//
// 2.) array loop and evaluate filters
//
TObjArray *selected = new TObjArray(10000); // TODO: we should get upper limit estimate from
Int_t nTrees=1;
if (tree->GetListOfFriends()!=NULL) nTrees+=tree->GetListOfFriends()->GetEntries();
for (Int_t iTree=0; iTree<nTrees; iTree++){
TTree * cTree = tree;
if (iTree>0) cTree=tree->GetFriend(tree->GetListOfFriends()->At(iTree-1)->GetName());
if (cTree==NULL) continue;
for (Int_t itype=0; itype<2; itype++){
// TTree::GetListOfAliases() is a TList
// TTree::GetListOfBranches is a TObjArray
TSeqCollection* elemList=0;
if (itype==0) elemList=cTree->GetListOfBranches();
if (itype==1) elemList=cTree->GetListOfAliases();
if (elemList==NULL) continue;
Int_t elemEntries=elemList->GetEntries();
for (Int_t ientry=0; ientry<elemEntries; ientry++){ // to be rewritten to TSeqColection iterator
TString elemName(elemList->At(ientry)->GetName());
//
for (Int_t icheck=0; icheck<formulaEntries; icheck++){ // check logical expression
formValue[icheck]=0;
if (formType[icheck]==0){ // check the name
if (formExact[icheck]==1) formValue[icheck]=(elemName==formMatch.At(icheck)->GetName());
if (formExact[icheck]==0) formValue[icheck]=(strstr(elemName.Data(),formMatch.UncheckedAt(icheck)->GetName())!=NULL);
}
if (formType[icheck]==1){ // check corresponding metadata
TObject* metaObject = TStatToolkit::GetMetadata(cTree,TString::Format("%s%s",elemName.Data(), formMatchType.UncheckedAt(icheck)->GetName()).Data());
if (metaObject){
TString metaName(metaObject->GetTitle());
if (formExact[icheck]==1) formValue[icheck]=(metaName==formMatch.At(icheck)->GetName());
if (formExact[icheck]==0) formValue[icheck]=(strstr(metaName.Data(),formMatch.UncheckedAt(icheck)->GetName())!=NULL);
}
}
}
Bool_t isSelected=pFormula->EvalPar(formValue.GetMatrixArray());
if (isSelected){
if (iTree==0) selected->AddLast(new TObjString(elemList->At(ientry)->GetName()));
if (iTree>0) selected->AddLast(new TObjString(TString::Format("%s.%s",tree->GetListOfFriends()->At(iTree-1)->GetName(),elemList->At(ientry)->GetName())));
if (verbose&0x1) printf("%s\n",elemName.Data());
}
}
}
}
return selected;
}
///
/// \param tree - input master tree pointer
/// \param infoType - array in which information is queried - "branch" "alias" "metaData" and logical or
/// \param regExpFriend - regular expression patter, where to seek (default empty - master tree)
/// \param regExpTag - regular expression tag to be queried - use non case sensitive Contain ( use as ^regExpTag$ to get full match )
/// \param verbose - verbosity flag
/// \return return selected string
TString AliTreePlayer::printSelectedTreeInfo(TTree *tree, TString infoType, TString regExpFriend, TString regExpTag,
Int_t verbose) {
/*
Example usage:
AliExternalInfo info;
TTree * treeTPC = info.GetTree("QA.TPC","LHC15o","cpass1_pass1","QA.TRD;QA.TPC;QA.TOC;QA.TOF;Logbook");
AliTreePlayer::printSelectedTreeInfo(treeTPC,"branch alias","","MIP",1);
-- print infoType ="branches or alias" containing regExpTag == MIP in the master tree
AliTreePlayer::printSelectedTreeInfo(treeTPC,"branch","QA.TRD","Eff",1);
-- print infoType ="branches" containing regExpTag == Eff in the QA.TRD tree
AliTreePlayer::printSelectedTreeInfo(treeTPC,"branch",".*","run",1)
-- print infoType ="branches" containing regExpTag == Eff in the all friend trees
AliTreePlayer::printSelectedTreeInfo(treeTPC,"branch",".*","^run$",1)
-- print infoType ="branches" containing regExpTag == run in the all friend trees
In case arrays or function should be selected - use aliases:
treeTPC->SetAlias("meanMIPvsSectorArray","meanMIPvsSector.fElements")'
treeTPC->SetAlias("runTypeName","runType.GetName()")
AliTreePlayer::printSelectedTreeInfo(treeTPC,"branch alias",".*","meanMIPvsSectorArray",1); ==> meanMIPvsSectorArray
AliTreePlayer::printSelectedTreeInfo(treeTPC,"branch alias ",".*","Name$",1) ==> runTypeName
*/
TString result = "";
TList *treeFriends = tree->GetListOfFriends();
Int_t ntrees = 1 + ((treeFriends != NULL) ? treeFriends->GetEntries() : 0);
TPRegexp pregExpFriend = regExpFriend;
TPRegexp pregExpTag = regExpTag;
const char *dataTypes[3] = {"branch", "alias", "metaData"};
for (Int_t itree = 0; itree < ntrees; itree++) {
TTree *currentTree = 0;
if (itree == 0) {
currentTree = tree;
if (pregExpFriend.Match(currentTree->GetName()) == 0) continue;
} else {
if (pregExpFriend.Match(treeFriends->At(itree - 1)->GetName()) == 0) continue;
currentTree = ((TFriendElement * )(treeFriends->At(itree - 1)))->GetTree();
}
if (verbose & 0x1) {
::Info("printSelectedTreeInfo", "tree %s selected", currentTree->GetName());
}
for (Int_t iDataType = 0; iDataType < 3; iDataType++) {
if (infoType.Contains(dataTypes[iDataType], TString::kIgnoreCase) == 0) continue;
TList *selList = 0;
if (iDataType == 0) selList = (TList *) currentTree->GetListOfBranches();
if (iDataType == 1) selList = (TList *) currentTree->GetListOfAliases();
if (iDataType == 2 && tree->GetUserInfo())
selList = (TList * )(currentTree->GetUserInfo()->FindObject("metaTable"));
if (selList == NULL) continue;
Int_t selListEntries = selList->GetEntries();
for (Int_t iEntry = 0; iEntry < selListEntries; iEntry++) {
if (pregExpTag.Match(selList->At(iEntry)->GetName()) <= 0) continue;
if (verbose & 0x1) {
::Info(" printSelectedTreeInfo", "%s.%s", currentTree->GetName(), selList->At(iEntry)->GetName());
}
if (result.Length() > 0) result += ":";
if (itree > 0) {
result += treeFriends->At(itree - 1)->GetName();
result += ".";
}
result += selList->At(iEntry)->GetName();
}
}
}
return result;
}
///
/// \param tree - input tree
/// \param what - variables to export (any valid TTree formula or class (in case ob JSON export))
/// \param where - selection criteria as in the TTree::Draw
/// \param firstentry - first entry in tree to export
/// \param nentries - number of entries to
/// \param outputFormat - output format (csv,json, elastic json - for bulk export,html table)
/// \param outputName
/// \return - status
Int_t AliTreePlayer::selectWhatWhereOrderBy(TTree * tree, TString what, TString where, TString /*orderBy*/, Int_t firstentry, Int_t nentries, TString outputFormat, TString outputName){
//
// Select entry similar to the SQL select
// tree instead - SQL FROM statement used
// - it is supposed that all information is contained in the tree and related friend trees
// - build tree with friends done in separate function
// what -
// code inspired by the TTreePlay::Scan but another treatment of arrays needed
// but wih few changes realted to different output formatting
// NOTICE:
// for the moment not all parameters used
// Example usage:
/*
AliTreePlayer::selectWhatWhereOrderBy(treeTPC,"run:Logbook.run:meanMIP:meanMIPele:meanMIPvsSector.fElements:fitMIP.fElements","meanMIP>0", "", 0,10,"html","qatpc.html");
*/
if (tree==NULL || tree->GetPlayer()==NULL){
::Error("AliTreePlayer::selectWhatWhereOrderBy","Input tree not defiend");
return -1;
}
// limit number of entries - shorter version of the TTreePlayer::GetEntriesToProcess - but not fully correct ()
if (firstentry +nentries >tree->GetEntriesFriend()) nentries=tree->GetEntriesFriend()-firstentry;
if (tree->GetEntryList()){ //
if (tree->GetEntryList()->GetN()<nentries) nentries=tree->GetEntryList()->GetN();
}
//
Int_t tnumber = -1;
Bool_t isHTML=outputFormat.Contains("html",TString::kIgnoreCase );
Bool_t isCSV=outputFormat.Contains("csv",TString::kIgnoreCase);
Bool_t isElastic=outputFormat.Contains("elastic",TString::kIgnoreCase);
Bool_t isJSON=outputFormat.Contains("json",TString::kIgnoreCase)||isElastic;
//
FILE *default_fp = stdout;
if (outputName.Length()>0){
default_fp=fopen (outputName.Data(),"w");
}
TObjArray *fArray=what.Tokenize(":");
Int_t nCols=fArray->GetEntries();
TObjArray *fFormulaList = new TObjArray(nCols+1);
TTreeFormula ** rFormulaList = new TTreeFormula*[nCols+1];
TObjString **printFormatList = new TObjString*[nCols]; // how to format variables
TObjString **columnNameList = new TObjString*[nCols];
TObjString **outputFormatList = new TObjString*[nCols]; // root header formatting
Bool_t isIndex[nCols];
Bool_t isParent[nCols];
TClass* isClass[nCols]; // is object
TPRegexp indexPattern("^%I"); // pattern for index
TPRegexp parentPattern("^%P"); // pattern for parent index
for (Int_t iCol=0; iCol<nCols; iCol++){
isClass[iCol]=NULL;
rFormulaList[iCol]=NULL;
TObjArray * arrayDesc = TString(fArray->At(iCol)->GetName()).Tokenize(";");
if (arrayDesc->GetEntries()<=0) {
::Error("AliTreePlayer::selectWhatWhereOrderBy","Invalid descriptor %s", arrayDesc->At(iCol)->GetName());
//return -1;
}
TString fieldName=arrayDesc->At(0)->GetName(); // variable content
if (tree->GetBranch(fieldName.Data())){
if (TString(tree->GetBranch(fieldName.Data())->GetClassName()).Length()>0) {
isClass[iCol]=TClass::GetClass(tree->GetBranch(fieldName.Data())->GetClassName());
}
}
if (fieldName.Contains(indexPattern)){ // variable is index
isIndex[iCol]=kTRUE;
indexPattern.Substitute(fieldName,"");
}else{
isIndex[iCol]=kFALSE;
}
if (fieldName.Contains(parentPattern)){ // variable is parent
isParent[iCol]=kTRUE;
parentPattern.Substitute(fieldName,"");
}else{
isParent[iCol]=kFALSE;
}
TTreeFormula * formula = NULL;
TNamed* htmlTag=TStatToolkit::GetMetadata(tree,(fieldName+".html").Data());
Bool_t isFormulaF= (fieldName[0]=='#') || htmlTag!=NULL;
if (!isFormulaF) {
formula=new TTreeFormula(fieldName.Data(), fieldName.Data(), tree);
}else {
TString fstring = fieldName;
if (htmlTag) {
fstring=htmlTag->GetTitle();
} else {
fieldName.Replace(0, 1, "");
if (tree->GetAlias(fieldName.Data())) {
fstring = tree->GetAlias(fieldName.Data());
}
}
formula=new AliTreeFormulaF(fieldName.Data(), fstring.Data(), tree);
}
if (formula->GetTree()==NULL){
::Error("AliTreePlayer::selectWhatWhereOrderBy","Invalid formula %s, parsed from the original string %s",fieldName.Data(),what.Data());
if (isJSON==kFALSE) return -1;
}
TString printFormat=""; // printing format - column 1 - use default if not specified
TString colName=arrayDesc->At(0)->GetName(); // variable name in ouptut - column 2 - using defaut ("variable name") as in input
TString outputFormat=""; // output column format specification for TLeaf (see also reading using TTree::ReadFile)
if (arrayDesc->At(1)!=NULL){ // format
printFormat=arrayDesc->At(1)->GetName();
}else{
if (formula->IsInteger()) {
printFormat="1.20";
}else{
printFormat="1.20";
}
}
if (arrayDesc->At(2)!=NULL) {
colName=arrayDesc->At(2)->GetName();
}else{
colName=arrayDesc->At(0)->GetName();
}
//colName = (arrayDesc->GetEntries()>1) ? arrayDesc->At(2)->GetName() : arrayDesc->At(0)->GetName();
if (arrayDesc->At(3)!=NULL){ //outputFormat (for csv)
outputFormat= arrayDesc->At(3)->GetName();
}else{
outputFormat="/D";
if (formula->IsInteger()) outputFormat="/I";
if (formula->IsString()) outputFormat="/C";
}
fFormulaList->AddAt(formula,iCol);
rFormulaList[iCol]=formula;
printFormatList[iCol]=new TObjString(printFormat);
outputFormatList[iCol]=new TObjString(outputFormat);
columnNameList[iCol]=new TObjString(colName);
}
TTreeFormula *select = new TTreeFormula("Selection",where.Data(),tree);
fFormulaList->AddLast(select);
rFormulaList[nCols]=select;
Bool_t hasArray = kFALSE;
Bool_t forceDim = kFALSE;
for (Int_t iCol=0; iCol<nCols; iCol++){
if (rFormulaList[iCol]!=NULL) rFormulaList[iCol]->UpdateFormulaLeaves();
if (rFormulaList[iCol]->GetManager()==NULL) continue; // TODO - check of needed for AliTreeFormulaF
// if ->GetManager()->GetMultiplicity()>0 mean there is at minimum one array
switch( rFormulaList[iCol]->GetManager()->GetMultiplicity() ) {
case 1:
case 2:
hasArray = kTRUE;
forceDim = kTRUE;
break;
case -1:
forceDim = kTRUE;
break;
case 0:
break;
}
}
// print header
if (isHTML){
fprintf(default_fp,"<table class=\"display\" cellspacing=\"0\" width=\"100%\">\n"); // add metadata info
fprintf(default_fp,"\t<thead class=\"header\">\n"); // add metadata info
fprintf(default_fp,"\t<tr>\n"); // add metadata info
for (Int_t iCol=0; iCol<nCols; iCol++){
TNamed *tHeadName = TStatToolkit::GetMetadata(tree,TString(columnNameList[iCol]->GetName())+".thead");
TNamed *tooltipName = TStatToolkit::GetMetadata(tree,TString(columnNameList[iCol]->GetName())+".tooltip");
TString sthName=(tHeadName!=NULL) ? tHeadName->GetTitle() : columnNameList[iCol]->GetName();
TNamed *descriptionName = TStatToolkit::GetMetadata(tree,TString(columnNameList[iCol]->GetName())+".headerTooltip");
fprintf(default_fp, "\t\t<th");
if (tooltipName!=0) fprintf(default_fp, " class=\"tooltip\" data-tooltip=\"%s\"", tooltipName->GetTitle());
if (descriptionName!=0) fprintf(default_fp, " title=\"%s\"", descriptionName->GetTitle());
fprintf(default_fp, ">%s</th>\n", sthName.Data()); // add metadata info
// if (tooltipName==NULL){
// fprintf(default_fp, "\t\t<th>%s</th>\n", sthName.Data()); // add metadata info
// }else {
// fprintf(default_fp, "\t\t<th class=\"tooltip\" data-tooltip=\"%s\">%s</th>\n", tooltipName->GetTitle(), sthName.Data()); // add metadata info
// }
}
fprintf(default_fp,"\t</tr>\n"); // add metadata info
fprintf(default_fp,"\t</thead>\n"); // add metadata info
//
fprintf(default_fp,"\t<tfoot class=\"header\">\n"); // add metadata info
fprintf(default_fp,"\t<tr>\n"); // add metadata info
for (Int_t iCol=0; iCol<nCols; iCol++){
fprintf(default_fp,"\t\t<th>%s</th>\n",columnNameList[iCol]->GetName()); // add metadata info
}
fprintf(default_fp,"\t</tr>\n"); // add metadata info
fprintf(default_fp,"\t</tfoot>\n"); // add metadata info
fprintf(default_fp,"\t<tbody>\n"); // add metadata info
}
if (isCSV){
// add header info
for (Int_t iCol=0; iCol<nCols; iCol++){
fprintf(default_fp,"%s%s",columnNameList[iCol]->GetName(), outputFormatList[iCol]->GetName());
if (iCol<nCols-1) {
fprintf(default_fp,":");
}else{
fprintf(default_fp,"\n"); // add metadata info
}
}
}
if (isJSON&&!isElastic){
fprintf(default_fp,"{\n\t \"tree\": [\n "); // add metadata info
}
Int_t selected=0;
for (Int_t ientry=firstentry; ientry<firstentry+nentries; ientry++){
Int_t entryNumber = tree->GetEntryNumber(ientry);
if (entryNumber < 0) break;
Long64_t localEntry = tree->LoadTree(entryNumber);
//
if (tnumber != tree->GetTreeNumber()) {
tnumber = tree->GetTreeNumber();
for(Int_t iCol=0;iCol<nCols;iCol++) {
rFormulaList[iCol]->UpdateFormulaLeaves();
}
select->UpdateFormulaLeaves();
}
if (select) {
// if (select->EvalInstance(inst) == 0) {
if (select->EvalInstance(0) == 0) { // for the moment simplified version of selection - not treating "array" selection
continue;
}
}
selected++;
// if json out
if (isJSON){
if (selected>1){
if (isElastic) {
fprintf(default_fp,"}\n{\"index\":{\"_id\": \"");
}
else{
fprintf(default_fp,"},\n{\n");
}
}else{
if (isElastic){
fprintf(default_fp,"{\"index\":{\"_id\": \"");
}else{
fprintf(default_fp,"{\n");
}
}
for (Int_t icol=0; icol<nCols; icol++){
TString obuffer="";
if (isClass[icol]){
const char*bname=rFormulaList[icol]->GetName();
TBranch *br = tree->GetBranch(bname);
br->GetEntry(entryNumber); // not sure if the entry is loaded
void **ppobject=(void**)br->GetAddress();
if (ppobject) {
obuffer = TBufferJSON::ConvertToJSON(*ppobject, isClass[icol]);
if (isElastic) obuffer.ReplaceAll("\n","");
//fprintf(default_fp,"%s",clbuffer.Data());
}
}
if (rFormulaList[icol]->GetTree()==NULL) continue;
Int_t nData=rFormulaList[icol]->GetNdata();
if (isJSON==kFALSE){
fprintf(default_fp,"\t\"%s\":",rFormulaList[icol]->GetName());
}else{
if (isIndex[icol]==kFALSE && isParent[icol]==kFALSE){
TString fieldName(rFormulaList[icol]->GetName());
if (isElastic) {
if (isClass[icol]) fieldName.Remove(fieldName.Length() - 1);
fieldName.ReplaceAll(".", "%_");
}
if (icol>0 && isIndex[icol-1]==kFALSE && isParent[icol-1]==kFALSE ){
fprintf(default_fp,"\t,\"%s\":",fieldName.Data());
}else{
fprintf(default_fp,"\t\"%s\":",fieldName.Data());
}
}
}
if (nData<=1){
if ((isIndex[icol]==kFALSE)&&(isParent[icol]==kFALSE)){
if (isClass[icol]!=NULL){
fprintf(default_fp,"%s",obuffer.Data());
}else {
if ( (isElastic || isJSON) && rFormulaList[icol]->IsString()) {
fprintf(default_fp, "\t\"%s\"",
rFormulaList[icol]->PrintValue(0, 0, printFormatList[icol]->GetName()));
} else {
fprintf(default_fp, "\t%s",
rFormulaList[icol]->PrintValue(0, 0, printFormatList[icol]->GetName()));
}
}
}
if (isIndex[icol]){
fprintf(default_fp,"%s",rFormulaList[icol]->PrintValue(0,0,printFormatList[icol]->GetName()));
if (isIndex[icol+1]){
fprintf(default_fp,".");
}else
if (isParent[icol+1]==kFALSE){
fprintf(default_fp,"\"}}\n{");
}
}
if (isParent[icol]==kTRUE){
fprintf(default_fp,"\", \"parent\": \"%s\"}}\n{",rFormulaList[icol]->PrintValue(0,0,printFormatList[icol]->GetName()));
}
}else{
fprintf(default_fp,"\t[");
for (Int_t iData=0; iData<nData;iData++){
fprintf(default_fp,"%f",rFormulaList[icol]->EvalInstance(iData));
if (iData<nData-1) {
fprintf(default_fp,",");
} else{
fprintf(default_fp,"]");
}
}
}
// if (icol<nCols-1 && (isIndex[icol]==kFALSE && isParent[icol]==kFALSE) ) fprintf(default_fp,",");
//fprintf(default_fp,"\n");
}
}
//
if (isHTML){
fprintf(default_fp,"<tr>\n");
for (Int_t icol=0; icol<nCols; icol++){
Int_t nData=rFormulaList[icol]->GetNdata();
if (nData<=1){
fprintf(default_fp,"\t<td>%s</td>",rFormulaList[icol]->PrintValue(0,0,printFormatList[icol]->GetName()));
}else{
fprintf(default_fp,"\t<td>");
for (Int_t iData=0; iData<nData;iData++){
fprintf(default_fp,"%f",rFormulaList[icol]->EvalInstance(iData));
if (iData<nData-1) {
fprintf(default_fp,",");
}else{
fprintf(default_fp,"</td>");
}
}
}
fprintf(default_fp,"\n");
}
fprintf(default_fp,"</tr>\n");
}
//
if (isCSV){
for (Int_t icol=0; icol<nCols; icol++){ // formula loop
Int_t nData=rFormulaList[icol]->GetNdata();
if (nData<=1){
fprintf(default_fp,"%s\t",rFormulaList[icol]->PrintValue(0,0,printFormatList[icol]->GetName()));
}else{
for (Int_t iData=0; iData<nData;iData++){ // array loo
fprintf(default_fp,"%f",rFormulaList[icol]->EvalInstance(iData));
if (iData<nData-1) {
fprintf(default_fp,",");
}else{
fprintf(default_fp,"\t");
}
}
}
}
fprintf(default_fp,"\n");
}
}
if (isJSON) fprintf(default_fp,"}\t]\n}\n");
if (isHTML){
fprintf(default_fp,"\t</tbody>"); // add metadata info
fprintf(default_fp,"</table>"); // add metadata info
}
if (default_fp!=stdout) fclose (default_fp);
return selected;
}
/// Get the enumeration type from a string
/// \param stat - enumuration tyle as a string
/// \return Get the enumeration type from a string
Int_t AliTreePlayer::GetStatType(const TString &stat){
if(!stat.CompareTo("median",TString::kIgnoreCase)){
return kMedian;
} else if(!stat.CompareTo("medianLeft",TString::kIgnoreCase)){
return kMedianLeft;
} else if(!stat.CompareTo("medianRight",TString::kIgnoreCase)){
return kMedianRight;
} else if(!stat.CompareTo("RMS",TString::kIgnoreCase)){
return kRMS;
} else if(!stat.CompareTo("Mean",TString::kIgnoreCase)){
return kMean;
}else if(!stat.CompareTo("Max",TString::kIgnoreCase)){
return kMax;
}else if(!stat.CompareTo("Min",TString::kIgnoreCase)){
return kMin;
} else if(stat.BeginsWith("LTMRMS",TString::kIgnoreCase)){ // Least trimmed RMS, argument is LTMRMS0.95 or similar
return kLTMRMS;
} else if(stat.BeginsWith("LTM",TString::kIgnoreCase)){ // Least trimmed mean, argument is LTM0.95 or similar
return kLTM;
} else {
::Error("GetStatType()","Cannot decode string \"%s\"."
" Use one of \"median\", \"medianLeft\", \"medianRight\", \"RMS\", or \"Mean\". "
" Also supported is \"LTM\", or \"LTMRMS\", which should be succeeded by a float like"
" \"LTM0.95\" or an integer (interpreted as percentage) like \"LTMRMS95\" to specify "
" the fraction of data to be kept."
" Use a colon separated list like \"median:medianLeft:medianRight:RMS\""
" as the fifth argument to the AddStatInfo().",stat.Data());
return kUndef;
}
}
///
/// \param treeLeft
/// \param treeRight
/// \param refQuery
/// \param deltaT
/// \param statString
/// \param maxEntries
void AliTreePlayer::AddStatInfo(TTree* treeLeft, TTree * treeRight , const TString refQuery, Double_t deltaT,
const TString statString,
Int_t maxEntries){
//
// 1.) Get variables from the right tree, sort them according to the coordinate
//
Int_t entries = treeRight->Draw(refQuery.Data(),"","goffpara",maxEntries);
if(entries<1){
::Error("AddStatInfo","No matching entries for query");
return;
}else if (entries>treeRight->GetEstimate()){
treeRight->SetEstimate(entries*2);
entries = treeRight->Draw(refQuery.Data(),"","goffpara",maxEntries);
}
Int_t * indexArr = new Int_t[entries];
TMath::Sort(entries, treeRight->GetV1(), indexArr,kFALSE);
Double_t * coordArray = new Double_t[entries];
for (Int_t icoord=0; icoord<entries; icoord++) coordArray[icoord]=treeRight->GetV1()[indexArr[icoord]];
//
// 2.) Attach the median,.. of the variables to the left tree
//
// The first token is the coordinate
TString var;
Ssiz_t from=0;
if(!refQuery.Tokenize(var,from,":")){
::Error("AddStatInfo","Cannot tokenize query \'%s\'. Use colon separated list"
,refQuery.Data());
delete[]indexArr;indexArr=0;
delete[]coordArray;coordArray=0;
return;
}
Int_t entriesCoord = treeLeft->GetEntries();
TBranch * br = treeLeft->GetBranch(var.Data());
Int_t coordValue;
br->SetAddress(&coordValue);
//TLeaf *coordLeaf = (TLeaf*)(br->GetListOfLeaves()->At(0));
while(refQuery.Tokenize(var,from,":")){
// var="valueAnodeRaw.fElements[0]";
TString stat;
Ssiz_t fromStat=0;
while(statString.Tokenize(stat,fromStat,":")){
// stat = "median"; stat="medianLeft"; stat="medianRight";
// Int_t statType=TStatToolkit::GetStatType(stat);
Int_t statType=GetStatType(stat);
if(statType==kUndef)continue;
//printf("\n\n\n--- StatType %d ---\n\n\n\n",statType);
// In case of LMS or LMR determine the fraction
Float_t frac=0.;
if(statType==kLTM || statType==kLTMRMS){ // stat="LTM0.95" or "LTMRMS0.95" similar
TString tmp= stat;
tmp.ReplaceAll("LTMRMS","");
tmp.ReplaceAll("LTM","");
frac = tmp.Atof(); // atof returns 0.0 on error
if(frac>1)frac/=100.; // allows "LTM95" for 95%
}
// Determine the offset in coordinate to the left and right
Double_t leftOffset=-1e99,rightOffset=-1e99;
if(statType==kMedian||statType==kRMS || statType==kMean
|| statType==kLTM || statType==kLTMRMS || statType==kMin || statType==kMax ){ // symmetric
leftOffset=-deltaT;rightOffset=deltaT;
} else if(statType==kMedianLeft){ //left
leftOffset=-2.*deltaT;rightOffset=0.;
} else if(statType==kMedianRight){ //right
leftOffset=0.;rightOffset=2.*deltaT;
}
TString brName=Form("%s_%s",var.Data(),stat.Data());
brName.ReplaceAll("[","_");
brName.ReplaceAll("]","_");
brName.ReplaceAll(".","_");
Double_t statValue=0;
if (treeLeft->GetDirectory()) treeLeft->GetDirectory()->cd();
TBranch *brToFill = treeLeft->Branch(brName.Data(),&statValue, (brName+"/D").Data());
TVectorD dvalues(entries);
for (Int_t icoord=0; icoord<entriesCoord; icoord++){
// Int_t icoord=0
br->GetEntry(icoord);
Double_t startCoord=coordValue+leftOffset;
Double_t endCoord =coordValue+rightOffset;
//Double_t startCoord=coordLeaf->GetValue()+leftOffset;
//Double_t endCoord =coordLeaf->GetValue()+rightOffset;
// Binary search finds last element smaller or equal
Int_t index0=BinarySearchSmaller(entries, coordArray, startCoord)+1;
Int_t index1=TMath::BinarySearch(entries, coordArray, endCoord) +1;
statValue=0;
if (index1>=0 && index0>=0){
//if (values.capacity()<index1-index0) values.reserve(1.5*(index1-index0)); //resize of needed