1 |
/*************************************************
|
2 |
Given a root file containing a TTree, this
|
3 |
macro will place half the contents into 2 new
|
4 |
files.
|
5 |
|
6 |
Can be run from a bash prompt as well:
|
7 |
root -b -l -q "splitTreeInFile.C(\"PhotonJetPt15_Summer09.root\",\"TreePhotonJet\")"
|
8 |
|
9 |
Or used within root:
|
10 |
$ root -l
|
11 |
root [0] .L splitTreeInFile.C
|
12 |
root [1] splitTreeInFile("PhotonJetPt15_Summer09.root","TreePhotonJet")
|
13 |
Opened PhotonJetPt15_Summer09.root...
|
14 |
Copying TreePhotonJet to two new files...
|
15 |
Created
|
16 |
PhotonJetPt15_Summer09_1stHalf.root
|
17 |
PhotonJetPt15_Summer09_2ndHalf.root
|
18 |
done.
|
19 |
root [2]
|
20 |
|
21 |
Michael B. Anderson
|
22 |
Oct 8, 2009
|
23 |
*************************************************/
|
24 |
|
25 |
|
26 |
void splitTreeInFile(TString origFilename, TString treeName) {
|
27 |
|
28 |
// Create names for the two new files
|
29 |
TString filenameString = origFilename;
|
30 |
filenameString.ReplaceAll(".root","");
|
31 |
TString newFilename1 = filenameString + "_1stHalf.root";
|
32 |
TString newFilename2 = filenameString + "_2ndHalf.root";
|
33 |
|
34 |
///////////////////////////////////////////////////////////
|
35 |
//Get old file, old tree and set top branch address
|
36 |
TFile *oldFile = new TFile(origFilename);
|
37 |
if (oldFile->IsZombie()) {
|
38 |
cout << "ERROR: " << origFilename << " not found" << endl;
|
39 |
return;
|
40 |
}
|
41 |
cout << "Opened " << origFilename << "..." << endl;
|
42 |
TTree *oldTree = (TTree*)oldFile->Get(treeName);
|
43 |
if (!oldTree) {
|
44 |
cout << "ERROR: " << treeName << " not found in " << origFilename << endl;
|
45 |
return;
|
46 |
}
|
47 |
Int_t numOfEntries = (Int_t)oldTree->GetEntries();
|
48 |
///////////////////////////////////////////////////////////
|
49 |
|
50 |
|
51 |
//Create a new file + a clone of old tree in new file
|
52 |
TFile *newFile1 = new TFile(newFilename1,"recreate");
|
53 |
TTree *newTree1 = oldTree->CloneTree(0);
|
54 |
TFile *newFile2 = new TFile(newFilename2,"recreate");
|
55 |
TTree *newTree2 = oldTree->CloneTree(0);
|
56 |
|
57 |
// Copy tree into new trees
|
58 |
cout << "Copying " << treeName << " to two new files..." << endl;
|
59 |
for (Int_t i=0;i<numOfEntries; i++) {
|
60 |
oldTree->GetEntry(i);
|
61 |
if (i<numOfEntries/2) {
|
62 |
newTree1->Fill();
|
63 |
} else {
|
64 |
newTree2->Fill();
|
65 |
}
|
66 |
}
|
67 |
|
68 |
newTree1->AutoSave();
|
69 |
newTree2->AutoSave();
|
70 |
newFile1->Close();
|
71 |
newFile2->Close();
|
72 |
cout << "Created\n " << newFilename1 << "\n " << newFilename2 << endl << "done." << endl;
|
73 |
}
|