Writing on files

This is a Python notebook in which you will practice the concepts learned during the lectures.

Startup ROOT

Import the ROOT module: this will activate the integration layer with the notebook automatically


In [ ]:
import ROOT

Writing histograms

Create a TFile containing three histograms filled with random numbers distributed according to a Gaus, an exponential and a uniform distribution. Close the file: you will reopen it later.


In [ ]:
rndm = ROOT.TRandom3(1)

filename = "histos.root"

# Here open a file and create three histograms

for i in xrange(1024):
    # Use the following lines to feed the Fill method of the histograms in order to fill
    rndm.Gaus()
    rndm.Exp(1)
    rndm.Uniform(-4,4)

# Here write the three histograms on the file and close the file

Now, you can invoke the ls command from within the notebook to list the files in this directory. Check that the file is there. You can invoke the rootls command to see what's inside the file.


In [ ]:
! ls .
! echo Now listing the content of the file
! rootls -l #filename here

Access the histograms and draw them in Python. Remember that you need to create a TCanvas before and draw it too in order to inline the plots in the notebooks. You can switch to the interactive JavaScript visualisation using the %jsroot on "magic" command.


In [ ]:
%jsroot on
f = ROOT.TFile(filename)
c = ROOT.TCanvas()
c.Divide(2,2)
c.cd(1)
f.gaus.Draw()
# finish the drawing in each pad
# Draw the Canvas

You can now repeat the exercise above using C++. Transform the cell in a C++ cell using the %%cpp "magic".


In [ ]:
%%cpp
TFile f("histos.root");
TH1F *hg, *he, *hu;
f.GetObject("gaus", hg);
// ... read the histograms and draw them in each pad

Inspect the content of the file: TXMLFile

ROOT provides a different kind of TFile, TXMLFile. It has the same interface and it's very useful to better understand how objects are written in files by ROOT. Repeat the exercise above, either on Python or C++ - your choice, using a TXMLFILE rather than a TFile and then display its content with the cat command. Can you see how the content of the individual bins of the histograms is stored? And the colour of its markers? Do you understand why the xml file is bigger than the root one even if they have the same content?


In [ ]:
f = ROOT.TXMLFile("histos.xml","RECREATE")

hg = ROOT.TH1F("gaus","Gaussian numbers", 64, -4, 4)
he = ROOT.TH1F("expo","Exponential numbers", 64, -4, 4)
hu = ROOT.TH1F("unif","Uniform numbers", 64, -4, 4)
for i in xrange(1024):
    hg.Fill(rndm.Gaus())
    # ... Same as above!

In [ ]:
! ls -l histos.xml histos.root

In [ ]:
! cat histos.xml