How to save objects in a File

TFile* f = TFile::Open("myfile.root",NEW);
TH1D* h1 = new TH1D(h1,h1,100,-5.,5.);
h1->FillRandom(gaus);  // fill histogram with random data
h1->Write();
delete f;

File Merging

  • ROOT file containing the same data objects (e.g. histograms, Trees, etc...) can be merged using the command line tool $ROOTSYS/bin/ hadd
$>  hadd  fileOut.root file1.root file2.root file3.root

How to Use Chains (Lists of Files)?

TChain object is a list of Root files containing the same tree. As an example, assume we have 3 Root files called file1.root, file2.root, file3.root. Each file contains one tree called "T". We can create a chain with the following statements:

TChain *chain=new TChain("tree");
   chain->Add("file1.root");
   chain->Add("file2.root");
   chain->Add("file3.root");

The class TChain is derived from the class TTree . For example, to generate an histogram corresponding to the attribute "x" in tree "tree" by processing sequentially the 3 files of this chain, we can do:

chain->Draw("x");

Chain files with loop

TChain *chain=new TChain("chain", "chainname");
const Int_t fNFile=11;
Int_t iFile;
for (iFile=0; iFile<fNFile; ++iFile) {
    chain->Add(Form("../anadata/CALIB_RUN%d.root", iFile+10));
}

Create new root file with cut from a existing tree

TFile *infile  = new TFile("input.root");
TFile *fout = new TFile("output.root","recreate");
((TTree*)infile->Get("tree"))->CopyTree("aoq<3.5&&aoq>3&&zet>49&&zet<51")
fout->Write();
fout->Close();

Read a subset of data(TTree branches)

• Faster to read – if you only want a subset of data members

• Slower to write due to the large number of branches

• For reading a subset of data recommend to use

TBranch* b_MyBranch;

tree->SetBranchAddress("MyBranch",&MyBranch,&b_MyBrancy);

b_MyBranch->GetEntry(ientry);//name of branch MyBranch

it will read only the required branch data (big difference in case of trees with many branches)

• Alternatively can use also

tree->SetBranchStatus("*", 0);
tree->SetBranchStatus(myBranch,1);

Scanning a Tree

  • Prints all the variables of the tree:
    MyTree->Scan("*");
    
  • Prints the values of var1, var2 and var3.
    MyTree->Scan("var1:var2:var3");
    
  • A selection can be applied in the second argument:
    • Prints the values of var1, var2 and var3 for the entries where var1 is greater than 0
MyTree->Scan("var1:var2:var3", "var1>0");

• Use the same syntax as TTree::Draw()

How to obtain more info from TTree::Draw

1. to TH

  • 1.按照ROOT默认的bin和范围画图
    tree->Draw("counts");        
    tree->Draw("counts>>h");     // 生成以"h"为名的histogram 
    tree->Draw("counts >>+ h")   // 如果已存在"h"为名的histogram,将数据追加到“h”上
    
  • 2.指定histogram
    tree->Draw("counts>>h(100, 0, 100)"    // nbin,xmin,xmax
    tree->Draw("counts>>h(100, 0, )"       // nbin,xmin,不指定xmax
    tree->Draw("counts>>h(100, ,100 )"       // nbin,不指定xmin,xmax
    
  • 3.先定义histogram
    TH1D *h1 = new TH1D("hoge", "hoge", 100, 0, 100);
    tree->Draw("counts>>hoge");
    
  • TH2,TH3 以此类推

  • 用2.的方式生成的histogram默认为Float_t型,对每个bin上的数有限制,在数目超过$10^5$时显示会有问题 (当前版本ROOT的bug)。此时推荐用3.的方式。

2. to TGraph

  • Once TTree::Draw has been called, it is possible to access useful information still stored in the TTree object via the following functions:

    -GetSelectedRows()    // return the number of entries accepted by the
                            //selection expression. In case where no selection
                            //was specified, returns the number of entries processed.
      -GetV1()              //returns a pointer to the float array of V1
      -GetV2()              //returns a pointer to the float array of V2
      -GetV3()              //returns a pointer to the float array of V3
      -GetW()               //returns a pointer to the double array of Weights
                            //where weight equal the result of the selection expression.
    

    where V1,V2,V3 correspond to the expressions in

    TTree::Draw("V1:V2:V3",selection);
    

    Example:

    tree->Draw("py:px","pz>4");
      TGraph *gr = new TGraph(tree->GetSelectedRows(),ntuple->GetV2(), ntuple->GetV1());
      gr->Draw("ap"); //draw graph in current pad creates a TGraph object with a number of points corresponding to the number of entries selected by the expression "pz>4", the x points of the graph being the px values of the Tree and the y points the py values.
    

    Important note: By default TTree::Draw creates the arrays obtained with GetV1, GetV2, GetV3, GetW with a length corresponding to the parameter fEstimate. By default fEstimate=10000 and can be modified via TTree::SetEstimate. A possible recipee is to do

    tree->SetEstimate(tree->GetEntries());
    

    You must call SetEstimate if the expected number of selected rows is greater than 10000.

You can use the option "goff" to turn off the graphics output of TTree::Draw in the above example.

3. to TVectorD

tree->Draw("x:y",tcut); // alternative: tr->Project("", "x:y", tcut);    
TVectorD *x_vec = new TVectorD(tree->GetSelectedRows(), tr->GetV1());    
TVectorD *y_vec = new TVectorD(tree->GetSelectedRows(), tr->GetV2());
  • "base" is given, number of bins and ranges are also printed
  • "range" is given, bin contents and errors are also printed for all bins in the current range (default 1–>nbins)
  • "all" is given, bin contents and errors are also printed for all bins including under and overflows.
h1->Print("base");

TH1.Print Name  = h, Entries= 172374006, Total sum= 1.70879e+06
          Title = e
          NbinsX= 10, xmin= 500, xmax=510

h1->Print("range");

TH1.Print Name  = h, Entries= 172374006, Total sum= 1.70879e+06
 fSumw[1]=106573, x=500.5
 fSumw[2]=114495, x=501.5
 fSumw[3]=124032, x=502.5
 fSumw[4]=122404, x=503.5
 fSumw[5]=117075, x=504.5
 fSumw[6]=120646, x=505.5
 fSumw[7]=132137, x=506.5
 fSumw[8]=163858, x=507.5
 fSumw[9]=258089, x=508.5
 fSumw[10]=449478, x=509.5

h1->Print("all");    

TH1.Print Name  = h, Entries= 172374006, Total sum= 1.70879e+06
 fSumw[0]=1.67772e+07, x=499.5
 fSumw[1]=106573, x=500.5
 fSumw[2]=114495, x=501.5
 fSumw[3]=124032, x=502.5
 fSumw[4]=122404, x=503.5
 fSumw[5]=117075, x=504.5
 fSumw[6]=120646, x=505.5
 fSumw[7]=132137, x=506.5
 fSumw[8]=163858, x=507.5
 fSumw[9]=258089, x=508.5
 fSumw[10]=449478, x=509.5
 fSumw[11]=1.67772e+07, x=510.5

histogram Draw()

gStyle->SetStatStyle(0);//remove statistics 
gStyle->SetPalette(1)//colz pattern

Convert TGraph g to TH2D h

int n=g->GetN();
double *x=g->GetX();
double *y=g->GetY();
for(int i=0;i<n;i++) h->Fill(x,y);
h->Draw("colz")

Adding points to a graph

  • Add point (x,y) to a grahp g
    g->SetPoint(g->GetN(), x,y)
    

在代码中运行脚本

gROOT->ProcessLine(".L anotherScript.c");
gROOT->ProcessLine("tree->Draw("x")");

to know if a file exists

if(gSystem->AccessPathName("test.txt")){
    std::cout << "test does not exist" << std::endl;
 } else {
    std::cout << "test exists" << std::endl;
 }

compile with root library

g++ Good.C `root-config --cflags` `root-config --glibs` -o Good