Professional Documents
Culture Documents
Lecture 4
W. H. Bell
University of Glasgow
C++ Programming for Physicists Page 1
Lecture Overview
● Strings
– Strings, Streams, Formatting
● C++ and Fortran 77
● Applications
– CLHEP
● HepMC
● Random
– Root
● Histograms
● Ntuples
● Trees
C++ Programming for Physicists Page 2
Strings
● Provided via the string STL container
– Includes inherited container member functions
– Allows the use of iterators and algorithms
● More functionality than cstring
● More obvious syntax
C++ Programming for Physicists Page 3
String Streams
● Can connect a stream to string: stringstream
– Allows stream syntax to parse or create string
C++ Programming for Physicists Page 4
C++ and Fortran
● C++ can be interfaced to many languages
– Fortran is often needed for physics applications
– Connecting Fortran to C++ allows access to tired and
testes programs.
● Fortran77 and C++ can be completely interfaced
but there are a few odd features.
– This course assumes g77 and g++ are used.
● Other f77 compilers may behave differently
C++ Programming for Physicists Page 5
Compiling Fortran77
● Fortran is not case sensitive
● Fortran function names are given one or two
underscores when compiled
● Fortran always uses pointers/references
● Fortran stores the length of a string in an implicit
integer variable and does not use '\0'
● Fortran array columns are C++ array rows
– Fortran counts from 1 by default
C++ Programming for Physicists Page 6
Calling Fortran from C++
extern "C" {
SUBROUTINE COMMONS
.... // Fortran subroutine COMMONS
void commons_(void);
END
Extract from ex4/fortran.for
} Extract from ex4/fortran.hh
SUBROUTINE LORENTZ(PA,PI,PF)
IMPLICIT NONE
REAL PA(4)
REAL PI(4)
REAL PF(4)
...
END Extract from ex5/lorentz.for
extern "C" {
void extern lorentz_(float [], float [], float []);
}
Extract from ex5/LorentzBoost.cc
C++ Programming for Physicists Page 7
Calling Fortran from C++
FUNCTION CALL_BACK(A,NAME)
IMPLICIT NONE
REAL A, C, CALL_BACK, MULT_A
CHARACTER*(*) NAME
RETURN
END Extract from ex4/fortran.for
extern "C" {
// Fortran function CALL_BACK
float call_back__(float *,char *, int);
}
Extract from ex4/fortran.hh
C++ Programming for Physicists Page 8
Calling C++ from Fortran
extern "C" {
float mult_a__(float *);
} Extract from ex4/fortran.hh
float mult_a__(float *a) {
return (*a)*10.;
} Extract from ex4/main.cc
FUNCTION CALL_BACK(A,NAME)
IMPLICIT NONE
REAL A, C, CALL_BACK, MULT_A
CHARACTER*(*) NAME
C = MULT_A(A)
CALL_BACK = C
RETURN
END Extract from ex4/fortran.for
C++ Programming for Physicists Page 9
Fortran Common Blocks
INTEGER INTARRAY(3,2)
REAL REALARRAY(2,3)
CHARACTER*50 SOMESTRING
COMMON/FORCOM/INTARRAY,REALARRAY,SOMESTRING
Extract from ex4/FORTRAN.INC
extern "C" {
typedef struct {
int intarray[2][3];
float realarray[3][2];
char somestring[50];
} forcom;
extern forcom forcom_;
} Extract from ex4/fortran.hh
● Array dimensions swap
● Only one definition within memory of
forcom_
C++ Programming for Physicists Page 10
Fortran Common Blocks
void fillCommon(void) {
for(int i=1;i<=2;i++) {
for(int j=1;j<=3;j++) {
forcom_.intarray[i1][j1] = i+j*10;
forcom_.realarray[j1][i1] = j+(float)i*0.001;
}
}
sprintf(forcom_.somestring,"C++ string");
}
Extract from ex4/main.cc
Filling a Fortran common block via an external struct
C++ Programming for Physicists Page 11
Using nm
C++ Programming for Physicists Page 12
Using nm
[user@machine ex4]$ nm -g main.o
U call_back__
U commons_ defined in fortran.o
U forcom_
U __gxx_personality_v0
00000000 T main
000000e4 T mult_a__ float mult_a__(float *a)
U sprintf
00000058 T _Z10fillCommonv
C++ Programming for Physicists Page 13
Working with other software
● Compile time – Include path 'g++ I'
● Link time – Library path 'g++ L'
● Run time LD_LIBRARY_PATH
C++ Programming for Physicists Page 14
CLHEP Introduction
● Provides basic classes for a range of particle and
nuclear physics applications
– Check if code has already been written
● This course was compiled with version 1.9.2.3
C++ Programming for Physicists Page 15
CLHEP Modules
● Units ● Evaluator
● Vector ● GenericFunctions
● Random ● HepPDT
● RandomObjects ● HepMC
● Geometry ● StdHep
● Matrix
C++ Programming for Physicists Page 16
CLHEP HepMC
C++ Programming for Physicists Page 17
CLHEP Random
● Contains random number engines and generators
– Engines provide the random numbers
● Provided with documentation references in the header files.
● Set the seed
– Generators use input random number to produce
another random distribution.
● Generators have static shoot member functions.
C++ Programming for Physicists Page 18
Examples of CLHEP Random
#include "CLHEP/Random/RanluxEngine.h"
#include "CLHEP/Random/RandGauss.h"
#include "CLHEP/Random/RandExponential.h"
long seed = 123456789;
RanluxEngine randomEngine(seed,4);
for(int i=0;i<10000;i++) {
dat[0] = RandGauss::shoot(&randomEngine);
dat[1] = RandExponential::shoot(&randomEngine);
}
Extract from ex4/Ntuples.cc
C++ Programming for Physicists Page 19
Root Introduction
An ObjectOriented Data Analysis Framework
● Endianless I/O – Used by most large PPE expts
– Histograms
– Ntuples
– Trees
● Graphical User Interface Libraries
● C++ Interpreted Environment via CINT
– Can compile or use interpreter
C++ Programming for Physicists Page 20
Root I/O from C++
● Create a TROOT object before anything else
– Provides a list of objects currently active.
● TFiles are part of this list.
● Create only one TROOT object.
– Do not use pointers
C++ Programming for Physicists Page 21
Root I/O from C++
● Anything which inherits from TObect can be
made persistent and written to a file.
– Calling the Write member function of this class or a
derived class causes:
● Object to be written to the current directory
● An associated key is defined according to the name
supplied
● Open file, produce histograms, and call Write.
C++ Programming for Physicists Page 22
TFile Summary
● When a ROOT file is opened it becomes the
current directory.
● Histograms and trees are automatically saved in
the file.
● When the file is closed the histogram and tree
objects associated with the file are deleted.
● Any object derived from TObject can be written
to a ROOT file. It has to be added explicitly.
C++ Programming for Physicists Page 23
Root I/O From C++
#include <TROOT.h>
#include <TFile.h> Include needed header files
#include <TH1.h>
int main(int argc, char *argv[]) {
TROOT simple("histos","Histogram Examples");
cout << "Opening root file: " << argv[1] << endl;
TFile *rfile = new TFile(argv[1],"RECREATE","Histogram
Example");
if(rfile==0) {
cout << "Could not create root file: " << argv[1] << endl;
return 0;
}
...histogramming...
rfile>Write();
return 0;
} Extract from ex6/Histograms.cc
C++ Programming for Physicists Page 24
Root Histograms
● Instantiate TROOT object
● Open TFile
Int_t nbinsx = 100;
Axis_t xlow = 0.0;
Axis_t xup = M_PI;
TH1F *histo = new TH1F("histo","Sine Wave",nbinsx,xlow,xup);
Axis_t x;
Stat_t w;
for(int i=1;i<=100;i++) {
x = M_PI/100.0*((double)i);
w = sin((double)x);
histo>Fill(x,w); Warning: Root uses lots of typedefs
} for standard types. Extract from ex6/Histograms.cc
● Close TFile
C++ Programming for Physicists Page 25
Simple Plotting via CINT
[user@machine ex6]$ root
root [0] new TBrowser();
C++ Programming for Physicists Page 26
Root TNtuples
● A simple TTree with TBranches of floats
– Inherits from TTree
● Can be thought of as a table of data where each
column is associated with a parameter.
C++ Programming for Physicists Page 27
TNtuple Example
● Instantiate TROOT object
● Open TFile
TNtuple *ntuple = new Tntuple("random_dat",
"Random Data","x:y:z");
Float_t dat[3];
for(int i=0;i<10000;i++) {
dat[0] = RandGauss::shoot(&randomEngine);
dat[1] = RandExponential::shoot(&randomEngine);
dat[2] = dat[0]*dat[1];
ntuple>Fill(dat);
} Extract from ex7/Ntuples.cc
● Close TFile
C++ Programming for Physicists Page 28
TTree
● TTree is a data structure of TBranches and
TLeaves.
– Each branch buffer can be individually accessed or
accessed all together
– Branches can be read from or written to different
files.
● Ideal for large numbers of events
– Allows compression of data
C++ Programming for Physicists Page 29
TTree Example
void writeTree(char *filename) {
Float_t x, y, z;
Int_t run, event;
TFile *root_file = TFile::Open(filename,"RECREATE");
if(!root_file) {
std::cerr << "Error: could not open root file "
<< filename << std::endl;
}
else {
TTree *tree = new TTree("tree","test tree");
tree>Branch("Run",&run,"Run/I");
tree>Branch("Event",&event,"Event/I");
tree>Branch("x",&x,"x/F");
tree>Branch("y",&y,"y/F");
tree>Branch("z",&z,"z/F");
...
Extract from ex8/Trees.cc
C++ Programming for Physicists Page 30
TTree Example
TRandom r;
for (Int_t i=0;i<10000;i++) {
if (i < 5000) {
run = 1;
}
else {
run = 2;
}
event = i;
x = r.Gaus(10,1);
y = r.Gaus(20,2);
z = r.Landau(2,1);
tree>Fill();
}
tree>Print();
root_file>Write();
delete root_file;
Extract from ex8/Trees.cc
C++ Programming for Physicists Page 31
TTree Example
TFile *root_file = TFile::Open(filename,"READ");
...
TTree *tree = (TTree*)root_file>Get("tree");
Int_t entries = tree>GetEntries();
TBranch *run_branch = tree>GetBranch("Run");
...
Float_t x, y, z;
Int_t run, event;
...
run_branch>SetAddress(&run);
...
for (Int_t i=0;i<10;i++) {
tree>GetEvent(i);
std::cout << event << " " << run << " "
<< x << " " << y << " " << z << std::endl;
}
Extract from ex8/Trees.cc
C++ Programming for Physicists Page 32
Exercises
● Session 4 examples:
– Download examples and course guide from
My.SUPA
● Download and build ROOT and CLHEP if needed
– Build and test examples
● Tutorial time should be used for consultation
C++ Programming for Physicists Page 33