]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/STEERBase/TTreeStream.cxx
Merge branch 'master' into TPCdev
[u/mrichter/AliRoot.git] / STEER / STEERBase / TTreeStream.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, 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 /* $Id$ */
17
18 //
19 //  marian.ivanov@cern.ch
20 //
21 //  ------------------------------------------------------------------------------------------------
22 //  TTreeStream
23 //  Standard stream (cout) like input for the tree
24 //  Run and see TTreeStreamer::Test() - to see TTreeStreamer functionality
25 //  ------------------------------------------------------------------------------------------------  
26 //
27 //  -------------------------------------------------------------------------------------------------
28 //  TTreeSRedirector
29 //  Redirect file to  different TTreeStreams  
30 //  Run and see   TTreeSRedirector::Test() as an example of TTreeSRedirectorer functionality 
31 // 
32
33 #include <TClass.h>
34 #include <TFile.h>
35 #include <TDirectory.h>
36 #include <TObjArray.h>
37 #include <TTree.h>
38 #include "TTreeStream.h"
39 // includes for test procedures
40 #include "TVectorD.h"
41 #include "TRandom.h"
42
43 ClassImp(TTreeDataElement)
44 ClassImp(TTreeStream)
45 ClassImp(TTreeSRedirector)
46
47
48
49 void TTreeStream::Test()
50 {
51   //
52   // 
53   TFile *ftest = new TFile("teststreamer.root","recreate");
54   if (!ftest) ftest = new TFile("teststreamer.root","new");
55   //
56   //create to streems Tree1 and Tree2
57   TTreeStream stream1("Tree1");
58   TTreeStream stream2("Tree2");
59   //
60   Char_t ch='s';
61   Float_t f=3.;
62   Float_t f2=1;
63   TObject *po  = new TObject;
64   TObject *po2 = new TObject;
65   for (Int_t i=0;i<100000;i++) {
66     f=i*100;
67     po->SetUniqueID(i);
68     po2->SetUniqueID(i*100);
69     ch=i%120;
70     //
71     //    Stream the data
72     //    The data layout of stream is defined during first invocation of streamer.
73     //    Endl is the trigger which define the end of structure.
74     // 
75     //    The name of branch can be specified using strings with = at the the end
76     //    if string is not specified automatic convention is u (sed B0, B1, ...Bn)
77     stream1<<"i="<<i<<"ch="<<ch<<"f="<<f<<"po="<<po<<"\n";
78     f  = 1./(100.1+i);
79     f2 = -f;     
80     //3.) just another example - we can fill the same tree with different objects
81     //
82     stream2<<f<<po<<"\n";
83     stream2<<f2<<po2<<"\n";
84   }
85   //
86   //4.) Close the streeamers (Write the streamed tree's to the file) and close the corresponding file.
87   //
88   stream1.Close();
89   stream2.Close();
90   ftest->Close();
91   delete ftest;
92   //
93   //5.) and now see results  in file tteststreamer.root
94 }
95
96 void TTreeSRedirector::Test2()
97 {
98   //
99   //Example test function to show functionality of TTreeSRedirector
100   //
101   //
102   //1.)create the  redirector associated with file (testredirector.root)
103   //
104   //
105   TFile* file = new TFile("test.root","recreate");
106   TTreeSRedirector *pmistream= new TTreeSRedirector();
107   TTreeSRedirector &mistream = *pmistream;
108   Char_t ch='s';
109   Float_t f=3.;
110   Float_t f2=1;
111   TObject *po  = new TObject;
112   TObject *po2 = new TObject;
113   for (Int_t i=0;i<100000;i++) {
114     f=i*100;
115     po->SetUniqueID(i);
116     po2->SetUniqueID(i*100);
117     ch=i%120;
118     //
119     //2.) create the tree with identifier specified by first argument
120     //                                layout specified by sequence of arguments
121     //                                Tree identifier has to be specified as first argument !!! 
122     //    if the tree and layout was already defined the consistency if layout is checked
123     //                                if the data are consisten fill given tree 
124     //    the name of branch can be specified using strings with = at the the end
125     //    if string is not specified use automatic convention  B0, B1, ...Bn
126     mistream<<"TreeIdentifier"<<"i="<<i<<"ch="<<ch<<"f="<<f<<"po="<<po<<"\n";
127     f  = 1./(100.1+i);
128     f2 = -f; 
129     
130     //3.) just another example - we can fill the same tree with different objects
131     //
132     mistream<<"TreeK"<<f<<po<<"\n";
133     mistream<<"TreeK"<<f2<<po2<<"\n";
134   }
135   //
136   //4.) write the streamed tree's to the file and close the corresponding file in destructor
137   //
138   delete pmistream;
139   delete file;
140   //
141   //5.) and now see results in file testredirector.root 
142 }
143
144 void TTreeSRedirector::Test()
145 {
146   //
147   //Example test function to show functionality of TTreeSRedirector
148   //
149   //
150   //1.)create the  redirector associated with file (testredirector.root)
151   //
152   //
153   TTreeSRedirector *pmistream= new TTreeSRedirector("testredirector.root");
154   TTreeSRedirector &mistream = *pmistream;
155   Char_t ch='s';
156   Float_t f=3.;
157   Float_t f2=1;
158   TObject *po  = new TObject;
159   TObject *po2 = new TObject;
160   for (Int_t i=0;i<100000;i++) {
161     f=i*100;
162     po->SetUniqueID(i);
163     po2->SetUniqueID(i*100);
164     ch=i%120;
165     //
166     //2.) create the tree with identifier specified by first argument
167     //                                layout specified by sequence of arguments
168     //                                Tree identifier has to be specified as first argument !!! 
169     //    if the tree and layout was already defined the consistency if layout is checked
170     //                                if the data are consisten fill given tree 
171     //    the name of branch can be specified using strings with = at the the end
172     //    if string is not specified use automatic convention  B0, B1, ...Bn
173     mistream<<"TreeIdentifier"<<"i="<<i<<"ch="<<ch<<"f="<<f<<"po="<<po<<"\n";
174     f  = 1./(100.1+i);
175     f2 = -f; 
176     
177     //3.) just another example - we can fill the same tree with different objects
178     //
179     mistream<<"TreeK"<<f<<po<<"\n";
180     mistream<<"TreeK"<<f2<<po2<<"\n";
181   }
182   //
183   //4.) write the streamed tree's to the file and close the corresponding file in destructor
184   //
185   delete pmistream;
186   //
187   //5.) and now see results in file testredirector.root 
188 }
189
190 void TTreeSRedirector::UnitTest(){
191   //
192   //
193   //
194   UnitTestSparse(0.5);
195   UnitTestSparse(0.1);
196   UnitTestSparse(0.01);
197 }
198
199 void TTreeSRedirector::UnitTestSparse(Double_t scale){
200   //
201   // Unit test for the TTreeSRedirector
202   // 1.) Test TTreeRedirector 
203   //      a.) Fill tree with random vectors
204   //      b.) Fill downscaled version of vectors
205   //      c.) The same skipping first entry
206   // 2.) Check results wtitten to terminale
207   //     a.) Disk consumption 
208   //             skip data should be scale time smaller than full
209   //             zerro replaced  ata should be compresed time smaller than full
210   //     b.) Test invariants
211   // Input parameter scale => downscaling of sprse element 
212   //            
213   if (scale<=0) scale=1;
214   if (scale>1) scale=1;
215   TTreeSRedirector *pcstream = new TTreeSRedirector("testpcstreamSparse.root","recreate");
216   for (Int_t ientry=0; ientry<20000; ientry++){
217     TVectorD vecRandom(50);
218     TVectorD vecZerro(50);   // zerro vector
219     for (Int_t j=0; j<50; j++) vecRandom[j]=ientry+gRandom->Rndm();
220     Bool_t isSelected= (gRandom->Rndm()<scale);
221     TVectorD *pvecFull   = &vecRandom;
222     TVectorD *pvecSparse = isSelected ? &vecRandom:0;
223     TVectorD *pvecSparse0 = isSelected ? &vecRandom:0;
224     TVectorD *pvecSparse1 = isSelected ? &vecRandom:&vecZerro;
225
226     if (ientry==0) {
227       pvecSparse0=0;
228       pvecSparse=&vecRandom;
229     }
230     (*pcstream)<<"Full"<<                  // stored all vectors
231       "ientry="<<ientry<<
232       "vec.="<<pvecFull<<                  
233       "\n";
234     (*pcstream)<<"SparseSkip"<<                // fraction of vectors stored
235       "ientry="<<ientry<<
236       "vec.="<<pvecSparse<<                
237       "\n";
238     (*pcstream)<<"SparseSkip0"<<               // fraction with -pointer
239       "ientry="<<ientry<<
240       "vec.="<<pvecSparse0<<
241       "\n";
242     (*pcstream)<<"SparseZerro"<<               // all vectors filled, franction filled with 0
243       "ientry="<<ientry<<
244       "vec.="<<pvecSparse1<<
245       "\n";
246   }
247   delete pcstream;
248   //
249   // 2.) check results
250   //
251   TFile* f = TFile::Open("testpcstreamSparse.root");
252   TTree * treeFull = (TTree*)f->Get("Full");
253   TTree * treeSparseSkip = (TTree*)f->Get("SparseSkip");
254   TTree * treeSparseSkip0 = (TTree*)f->Get("SparseSkip0");
255   TTree * treeSparseZerro = (TTree*)f->Get("SparseZerro");
256   //    a.) data volume
257   //
258   Double_t ratio=(1./scale)*treeSparseSkip->GetZipBytes()/Double_t(treeFull->GetZipBytes());
259   Double_t ratio0=(1./scale)*treeSparseSkip0->GetZipBytes()/Double_t(treeFull->GetZipBytes());
260   Double_t ratio1=(1./scale)*treeSparseZerro->GetZipBytes()/Double_t(treeFull->GetZipBytes());
261   printf("#UnitTest:\tTTreeSRedirector::TestSparse(%f)\tRatioSkip\t%f\n",scale,ratio);
262   printf("#UnitTest:\tTTreeSRedirector::TestSparse(%f)\tRatioSkip0\t%f\n",scale,ratio0);
263   printf("#UnitTest:\tTTreeSRedirector::TestSparse(%f)\tRatioZerro\t%f\n",scale,ratio1);
264   //    b.) Integrity 
265   Int_t outlyersSparseSkip=treeSparseSkip->Draw("1","(vec.fElements-ientry-0.5)>0.5","goff");
266   Int_t outlyersSparseSkip0=treeSparseSkip0->Draw("1","(vec.fElements-ientry-0.5)>0.5","goff");
267   printf("#UnitTest:\tTTreeSRedirector::TestSparse(%f)\tOutlyersSkip\t%d\n",scale,outlyersSparseSkip);
268   printf("#UnitTest:\tTTreeSRedirector::TestSparse(%f)\tOutlyersSkip0\t%d\n",scale,outlyersSparseSkip);
269
270   Bool_t isOK=(ratio<1.2)&&(outlyersSparseSkip0);
271   printf("#UnitTest:\tTTreeSRedirector::TestSparse(%f)\tisOk\t%d\n",scale,isOK);  
272 }
273
274 TTreeSRedirector::TTreeSRedirector(const char *fname,const char * option) :
275   fDirectory(NULL),
276   fDirectoryOwner(kTRUE),
277   fDataLayouts(NULL)
278 {
279   //
280   // Constructor
281   //
282   TString name(fname);
283   if (!name.IsNull()){
284     fDirectory = new TFile(fname,option);
285   }
286   else
287   {
288     fDirectory = gDirectory;
289     fDirectoryOwner = kFALSE;
290   }
291 }
292
293 TTreeSRedirector::~TTreeSRedirector()
294 {
295   //
296   // Destructor
297   //
298   Close();       //write the tree to the selected file
299   if (fDirectoryOwner)
300   {
301     fDirectory->Close();
302     delete fDirectory;
303   }
304 }
305 void TTreeSRedirector::StoreObject(TObject* object){
306   //
307   //
308   //
309   TDirectory * backup = gDirectory;
310   fDirectory->cd();
311   object->Write();
312   if (backup) backup->cd();
313 }
314
315 void  TTreeSRedirector::SetDirectory(TDirectory *sfile){
316   //
317   // Set the external file 
318   // In case other file already attached old file is closed before
319   // Redirector will be the owner of file ?
320   if (fDirectory && fDirectoryOwner) {
321     fDirectory->Close();
322     delete fDirectory;
323   }
324   fDirectory=sfile;
325 }
326
327 TTreeStream  & TTreeSRedirector::operator<<(Int_t id)
328 {
329   //
330   // return reference to the data layout with given identifier
331   // if not existing - creates new
332   if (!fDataLayouts) fDataLayouts = new TObjArray(10000);
333   TTreeStream *clayout=0;
334   Int_t entries = fDataLayouts->GetEntriesFast();
335   for (Int_t i=0;i<entries;i++){
336     TTreeStream * layout = (TTreeStream*)fDataLayouts->At(i);
337     if (!layout) continue;
338     if (layout->fId==id) {
339       clayout = layout;
340       break;
341     }
342   }
343   if (!clayout){
344     TDirectory * backup = gDirectory;
345     fDirectory->cd();
346     char chname[100];
347     snprintf(chname,100,"Tree%d",id);
348     clayout = new TTreeStream(chname);
349     clayout->fId=id;
350     fDataLayouts->AddAt(clayout,entries);
351     if (backup) backup->cd();
352   }
353   return *clayout;
354 }
355
356 void TTreeSRedirector::SetExternalTree(const char* name, TTree* externalTree)
357 {
358   TTreeStream *clayout=(TTreeStream*)fDataLayouts->FindObject(name);
359
360   if (!clayout){
361     TDirectory * backup = gDirectory;
362     fDirectory->cd();
363     clayout = new TTreeStream(name,externalTree);
364     clayout->fId=-1;
365     clayout->SetName(name);
366     Int_t entries = fDataLayouts->GetEntriesFast();
367     fDataLayouts->AddAt(clayout,entries);
368     if (backup) backup->cd();
369   }
370   //else
371   //  AliError(Form("identifier %s already associated",name));
372 }
373
374
375 TTreeStream  & TTreeSRedirector::operator<<(const char* name)
376 {
377   //
378   // return reference to the data layout with given identifier
379   // if not existing - creates new
380   if (!fDataLayouts) fDataLayouts = new TObjArray(10000);
381   TTreeStream *clayout=(TTreeStream*)fDataLayouts->FindObject(name);
382   Int_t entries = fDataLayouts->GetEntriesFast();
383
384   if (!clayout){
385     TDirectory * backup = gDirectory;
386     fDirectory->cd();
387     clayout = new TTreeStream(name);
388     clayout->fId=-1;
389     clayout->SetName(name);
390     fDataLayouts->AddAt(clayout,entries);    
391     if (backup) backup->cd();
392   }
393   return *clayout;
394 }
395
396
397
398
399 void TTreeSRedirector::Close(){
400   //
401   //
402   TDirectory * backup = gDirectory;
403   fDirectory->cd();
404   if (fDataLayouts){
405     Int_t entries = fDataLayouts->GetEntriesFast();
406     for (Int_t i=0;i<entries;i++){
407       TTreeStream * layout = (TTreeStream*)fDataLayouts->At(i);
408       if (layout){
409         if (layout->fTree) layout->fTree->Write(layout->GetName());
410       }
411     }
412     delete fDataLayouts;
413     fDataLayouts=0;
414   }
415   if (backup) backup->cd();
416 }
417
418 //-------------------------------------------------------------
419 TTreeDataElement:: TTreeDataElement(Char_t type) :
420   TNamed(),
421   fType(type),
422   fDType(0),
423   fClass(0),
424   fPointer(0)
425 {
426   //
427   //
428   //
429 }
430
431 TTreeDataElement:: TTreeDataElement(TDataType* type) :
432   TNamed(),
433   fType(0),
434   fDType(type),
435   fClass(0),
436   fPointer(0)
437 {
438   //
439   //
440   //
441 }
442
443 TTreeDataElement:: TTreeDataElement(TClass* cl) :
444   TNamed(),
445   fType(0),
446   fDType(0),
447   fClass(cl),
448   fPointer(0)
449 {
450   //
451   //
452   //
453 }
454
455 //-------------------------------------------------------------------
456 TTreeStream::TTreeStream(const char *treename, TTree* externalTree):
457   TNamed(treename,treename),
458   fElements(0),
459   fBranches(0),
460   fTree(externalTree),
461   fCurrentIndex(0),
462   fId(0),
463   fNextName(),
464   fNextNameCounter(),
465   fStatus(0)
466 {
467   //
468   // Standard ctor
469   //
470   if (!fTree) fTree = new TTree(treename, treename);
471 }
472
473 TTreeStream::~TTreeStream()
474 {
475   //
476   // Class dtor
477   //
478   fElements->Delete();
479   fBranches->Clear();
480   delete fElements;
481   delete fBranches;
482 }
483
484 void TTreeStream::Close()
485 {
486   //
487   // Flush data to disk and close
488   //
489   fTree->Write();
490 }
491
492 Int_t TTreeStream::CheckIn(Char_t type, void *pointer)
493 {
494   //
495   // Insert object of given type
496   //
497   if (!fElements) fElements = new TObjArray(10000);
498   if (fElements->GetSize()<=fCurrentIndex) fElements->Expand(fCurrentIndex*2);
499   TTreeDataElement* element = (TTreeDataElement*)fElements->At(fCurrentIndex);
500   if (!element) {
501     element = new TTreeDataElement(type);
502     //
503     char name[1000];
504     if (fNextName.Length()>0){
505       if (fNextNameCounter==0){
506         snprintf(name,1000,"%s",(const char*)fNextName);
507       }
508       if (fNextNameCounter>0){
509         snprintf(name,1000,"%s%d",(const char*)fNextName,fNextNameCounter);
510       }      
511     }
512     else{
513       snprintf(name,1000,"B%d.",fCurrentIndex);
514     }
515     element->SetName(name);
516     //
517     element->SetPointer(pointer);
518     fElements->AddAt(element,fCurrentIndex);
519     fCurrentIndex++;
520     return 0; //new element added
521   }
522   if (element->GetType()!=type){
523     fStatus++;
524     return 1; //mismatched data element
525   }
526   element->SetPointer(pointer);
527   fCurrentIndex++;
528   return 0;
529 }
530
531 Int_t TTreeStream::CheckIn(TObject *pObject){
532   //
533   // Insert TObject
534   //
535   TClass *pClass = 0;
536   if (pObject) pClass=pObject->IsA();
537   if (!fElements) fElements = new TObjArray(1000);
538   TTreeDataElement* element = (TTreeDataElement*)fElements->At(fCurrentIndex);
539   if (!element) {
540     element = new TTreeDataElement(pClass);
541     //
542     char name[1000];
543     if (fNextName.Length()>0){
544       if (fNextNameCounter==0){
545         snprintf(name,1000,"%s",(const char*)fNextName);
546       }
547       if (fNextNameCounter>0){
548         snprintf(name,1000,"%s%d",(const char*)fNextName,fNextNameCounter);
549       }      
550     }
551     else{
552       snprintf(name,1000,"B%d",fCurrentIndex);
553     }
554     element->SetName(name);
555     
556     element->SetPointer(pObject);
557     fElements->AddAt(element,fCurrentIndex);
558     fCurrentIndex++;
559     return 0; //new element added
560   }
561   if (element->fClass==0) {
562     element->fClass=pClass;
563   }else{
564     if (element->fClass!=pClass){
565       fStatus++;
566       return 1; //mismatched data element
567     }
568   }
569   element->SetPointer(pObject);
570   fCurrentIndex++;
571   return 0;  
572 }
573
574 void TTreeStream::BuildTree(){
575   //
576   // Build the Tree
577   //
578   //if (fTree && fTree->GetEntries()>0) return;
579   if (!fTree)  fTree = new TTree(GetName(),GetName());
580   Int_t entries = fElements->GetEntriesFast();  
581   if (!fBranches) fBranches = new TObjArray(entries);
582   
583   for (Int_t i=0;i<entries;i++){
584     //
585     TTreeDataElement* element = (TTreeDataElement*)fElements->At(i);
586     if (fBranches->At(i)) continue;
587     char bname1[1000];
588     if (element->GetName()[0]==0){
589       snprintf(bname1,1000,"B%d",i);
590     }
591     else{
592       snprintf(bname1,1000,"%s",element->GetName());
593     }
594     if (element->fClass){
595       if (element->fClass->GetBaseClass("TClonesArray")){
596         TBranch * br = fTree->Branch(bname1,element->fClass->GetName(),&(element->fPointer));
597         fBranches->AddAt(br,i);
598       }else
599         {
600           TBranch * br = fTree->Branch(bname1,element->fClass->GetName(),&(element->fPointer));
601           fBranches->AddAt(br,i);
602         }
603     }
604     if (element->GetType()>0){
605       char bname2[1000];
606       snprintf(bname2,1000,"B%d/%c",i,element->GetType());
607       TBranch * br = fTree->Branch(bname1,element->fPointer,bname2);
608       fBranches->AddAt(br,i);
609     }
610   }
611 }
612
613 void TTreeStream::Fill(){
614   //
615   // Fill the tree
616   //
617   if (fTree) { 
618     Int_t entries=fElements->GetEntriesFast();
619     if (entries>fTree->GetNbranches()) BuildTree();
620     for (Int_t i=0;i<entries;i++){    
621       TTreeDataElement* el  = (TTreeDataElement*)fElements->At(i);
622       if (!el) continue;
623       if (!el->GetType()) continue;
624       TBranch      * br  = (TBranch*)fBranches->At(i);
625       if (br &&el){
626         if (el->GetType())  br->SetAddress(el->fPointer);
627       }
628     }
629     if (fStatus==0) fTree->Fill(); //fill only in case of non conflicts
630     fStatus=0;
631   }
632 }
633
634 TTreeStream & TTreeStream::Endl()
635 {
636   //
637   // Perform pseudo endl operation
638   //
639   if (fTree->GetNbranches()==0) BuildTree();
640   Fill();
641   fStatus =0;
642   fCurrentIndex=0;
643   return *this;
644 }
645
646
647 TTreeStream  &TTreeStream::operator<<(const Char_t *name)
648 {
649   //
650   // Endl 
651   //
652   if (name[0]=='\n'){
653     return Endl();
654   }
655   //
656   //if tree was already defined ignore
657   if (fTree->GetEntries()>0) return *this;
658   //check branch name if tree was not 
659   //
660   Int_t last=0;
661   for (last=0;;last++){
662     if (name[last]==0) break;    
663   }
664   
665   if (last>0&&name[last-1]=='='){
666     fNextName = name;
667     fNextName[last-1]=0;
668     fNextNameCounter=0;
669   }
670   return *this;
671 }
672