4.2.4.4 Exercise 04: How to analyse PAT Candidates
Contents
Objectives
In this example you will learn
how to access the information from a PAT candidate with a simple piece of code that can easily be transformed into an EDAnalyzer or an FWLite executable. We also show you how you can very easily dump selected information of a
pat::Tuple or a RECO or AOD file into into a customized and
EDM-compliant user n-tuple, without writing a single line of C++ code. You can find all examples presented on this TWiki page in the
PatExamples
package. They will provide you with the following information:
- How to create a plugin or a bare executable within a CMSSW package.
- How to book a histogram using the TFileService within full CMSSW or FWLite.
- How to access the information of a PAT candidate within a common EDAnalyzer.
For this example we picked the
pat::Muon collection. You can transform everything you learn to any other
pat::Candidate by replacing the
reco::Muon data format and labels by the corresponding data format and labels of the collection of your interest. An example of how to do such a replacement is given at the
end of the page. A few questions will help you to check your learning success. After going through these explanation you should be well equipped to solve the
Exercises at the end of the page.
Note:
This web course is part of the
PAT Tutorial, which takes place regularly at CERN and other places. When following the PAT Tutorial, the answers to questions marked in
RED should be filled into the exercise form that has been introduced at the beginning of the tutorial. The solutions to the
Exercises should also be filled into the form. The exercises are marked in three colours, indicating whether the exercise is basic (obligatory), continuative (recommended), or optional (free). The colour-coding is summarized in the table below:
Color Code |
Explanation |
|
Basic exercise, which is obligatory for the PAT Tutorial. |
|
Continuative exercise, which is recommended for the PAT Tutorial, to deepen what has been learned. |
|
Optional exercise, which shows interesting applications of what has been learned. |
Basic exercises (

) are mandatory and the solutions to the exercises should be filled into the exercise form during the PAT Tutorial.
Setting up the environment
First of all, connect to
lxplus
and go to some work directory. You can choose any directory, provided that you have enough space—you need ~5 MB of free disc space for this exercise. We recommend that you use your
~/scratch0 space. In case you don't have this (or don't even know what it is), check your quota by typing
fs lq
and following
this link
. If you don't have enough space, you may instead use the temporary space (
/tmp/your_user_name), but be aware that this is lost once you log out of lxplus (or within something like a day). We assume in the following tutorial that you are using your
~/scratch0 directory.
ssh your_lxplus_name@lxplus6.cern.ch
[ ... enter password ... ]
cd scratch0/
Create a new directory for this exercise (in order to avoid interference with code from the other exercises) and enter it.
mkdir exercise04
cd exercise04
Create a local release area and enter it.
cmsrel CMSSW_7_4_1_patch4
cd CMSSW_7_4_1_patch4/src
The first command creates all directories needed in a local release area. Setting up the environment is done invoking the following script:
cmsenv
How to get the code
The
PatExamples
package is part of all CMSSW releases. To be able to inspect and to work on the examples described below, you should add the package to your
src directory and compile it. To achieve this do the following:
git cms-addpkg PhysicsTools/PatAlgos
git cms-addpkg PhysicsTools/PatExamples
git cms-merge-topic -u CMS-PAT-Tutorial:CMSSW_7_4_1_patTutorial
scram b -j 4
Note: Compiling is accomplished with the
scram b
command. To make use of more than one core to compile packages, we use of the
scram
compiler flag
-j
followed by the number of cores we would like to make use of.
This will checkout the
PatAlgos and
PatExamples packages from the central release area for CMSSW_7_4_1_patch4.
Note: For the following examples you need to produce a PAT tuple with the name
patTuple.root beforehand. It can be generated using the
patTuple_standard_cfg.py
either from from the
PatExamples or from the
PatAlgos package. We will make use of the file in the
PatExamples package:
cmsRun PhysicsTools/PatAlgos/test/patTuple_standard_cfg.py
Have a look to the
WorkBookPATTupleCreationExercise to learn more about the creation of PAT tuples.
How to access information from a pat::Candidate with an EDAnalyzer or FWLite
We will first show to access the information of a
pat::Candidate with a full framework EDAnalyzer or FWLite executable. We show how this can be done very conveniently using the principle of the BasicAnalyzer as defined in the
PhysicsTools/UtilAlgos
package.
How to run the EDAnalyzer example
To run the EDAnalyzer example on the newly created PAT tuple do the following:
cmsRun PhysicsTools/PatExamples/test/analyzePatMuons_edm_cfg.py
You will receive a root file with name
analyzePatMuons.root which will contain a set of histograms in a directory
patMuonAnalyzer. Open the root file that will have been produced by typing:
root -l analyzePatMuons.root
Question 4 a): When you produced the patTuple.root file from the patTuple_standard_cfg.py as recommended above you were using a standard pythia ttbar MC file as input. What is the mean muon pt of the muons that you find in this sample?
Note: The file and directory names are defined by a parameter of the
TFileService
and by the name of the module in the configuration file that is described
below. The histograms are registered in the
beginJob function of the
PatMuonAnalyzer class that is described below. They contain the
pt,
eta and
phi of all muons in the event.
Note: You would do an analysis within the full framework, when running complex large scale analyses, which make full use of the
EDM event content (e.g. when reading objects from but also writing objects into the event) and when running with the help of
crab or local batch systems.
Let us have a look at the configuration file:
import FWCore.ParameterSet.Config as cms
process = cms.Process("Test")
process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( "file:patTuple_standard.root" ) ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )
## --- ## This is an example of the use of the BasicAnalyzer concept used to exploit C++ classes to do anaysis ## in full framework or FWLite using the same class. You can find the implementation of this module in ## PhysicsTools /PatExamples/plugins/PatMuonEDAnlyzer.cc. You can find the EDAnalyzerWrapper.h class in ## PhysicsTools /UtilAlgos/interface/EDAnalyzerWrapper.h. You can find the implementation of the ## PatMuonAnalyzer class in PhysicsTools /PatExamples/interface/PatMuonAnlyzer.h. You will also find # # back the input parameters to the module.
process.patMuonAnalyzer = cms.EDAnalyzer("PatMuonEDAnalyzer", muons = cms.InputTag("selectedPatMuons"), )
process.TFileService = cms.Service("TFileService", fileName = cms.string('analyzePatMuons.root') )
process.p = cms.Path(process.patMuonAnalyzer)
Note: You can find the definition of the input file (
patTuple_standard.root), the definition of the full framework module of our BasicAnalyzer (
patMuonAnalyzer) and the definition of the
TFileService, which is configured to book the histograms of all registered EDAnalyzers in a histogram file with name
analyzePatMuons.root. This histogram file will contain a folder with the name of our EDAnalyzer module, in which you find the set of histograms that we have booked in the implementation of the
PatMuonAnalyzer. In the module definition the
edm::InputTag for the
pat::Muon collections is given. Have a look into the constructor of the
module implementation to see, how this
edm::InputTag is passed on the the analyzer code. Have a look to
WorkBookPATDataFormats to find out what collection labels are available (after running the default workflow). Have a look to
WorkBookPATWorkflow to find out how they are produced and what they mean.
Question 4 b): For more complex cfg files the definition of the module could be kept in an extra cfi file, which could be loaded into the main configuration file instead of having the module definition being part of the cfg file. How would you do that? (Have a look at WorkBookConfigFileIntro#ConfigContents for some hints).
How to run the FWLite example
To fill the same histograms using an FWLite executable. Do the following:
PatMuonFWLiteAnalyzer PhysicsTools/PatExamples/test/analyzePatMuons_fwlite_cfg.py
You will get the same output as for the full framework example that has been demonstrated above. Note the difference in speed. Also the FWLite executable can be configured using the CMS python configuration language in analogy to the full framework example. The configuration file in our example is given below:
import FWCore.ParameterSet.Config as cms
process = cms.PSet()
process.fwliteInput = cms.PSet( fileNames = cms.vstring('file:patTuple_standard.root'), ## mandatory
maxEvents = cms.int32(100), ## optional
outputEvery = cms.uint32(10), ## optional )
process.fwliteOutput = cms.PSet( fileName = cms.string('analyzePatMuons.root'), ## mandatory )
process.patMuonAnalyzer = cms.PSet( ## input specific for this analyzer muons = cms.InputTag('selectedPatMuons') )
Note: The key element of the configuration is the
edm::ParameterSet process. This should contain another
edm::ParameterSet process.fwliteInput to define the the input histogram, the number of events to be processed and whether or not and when there should be an output printed to the screen. The latter two parameters are optional. If omitted default values will be picked up. Another mandatory
edm::ParameterSet in the configuration file is the
process.fwliteOutput, where the name of the output file is defined. The
edm::ParameterSet with name
process.patMuonAnalyzer defines the parameters, which are important for the actual implementation of our
PatMuonAnalyzer class. Have a look to the instantiation of the
FWLite executable below and the explanations there to learn how the the name of the
process.patMuonAnalyzer PSet is passed on to the actual implementation.
Note: In FWLite there is no other interaction with the
EDM event content but reading. You can view FWLite executables as a safer (and more convenient) way to write compiled interactive root macros. You would do an analysis within FWLite, when performing smaller studies on the basis of (compiled) root macros. As a rule of thumb it make sense to run FWLite executable, if their complexity is not significantly larger than that of a typical single EDAnalyzer.
The implementation of the PatMuonAnalyzer
In the example above we were using the same physical piece of code for the plugin that you ran using
cmsRun and the FWLite executable. This concept gives you a lot of flexibility in the decision whether you want to use a full framework module for your analysis, that you might want to run with a batch system or via the grid or whether you want to do a quick study using FWLite. You can find the class declaration in
PhysicsTools/PatExamples/interface/PatMuonAnalyzer.h
:
#include <map> #include <string>
#include "TH1.h" #include "PhysicsTools/UtilAlgos/interface/BasicAnalyzer.h" #include "DataFormats/PatCandidates/interface/Muon.h"
/** \class PatMuonAnalyzer PatMuonAnalyzer.h "PhysicsTools/PatExamples/interface/PatMuonAnalyzer.h"
\brief Example class that can be used to analyze pat::Muons both within FWLite and within the full framework
This is an example for keeping classes that can be used both within FWLite and within the full framework. The class is derived from the BasicAnalyzer base class, which is an interface for the two wrapper classes EDAnalyzerWrapper and FWLiteAnalyzerWrapper. You can fin more information on this on WorkBookFWLiteExamples#ExampleFive. */
class PatMuonAnalyzer : public edm::BasicAnalyzer {
public: /// default constructor PatMuonAnalyzer (const edm::ParameterSet& cfg, TFileDirectory & fs); PatMuonAnalyzer (const edm::ParameterSet& cfg, TFileDirectory & fs, edm::ConsumesCollector&& iC); /// default destructor virtual ~PatMuonAnalyzer(){}; /// everything that needs to be done before the event loop void beginJob(){}; /// everything that needs to be done after the event loop void endJob(){}; /// everything that needs to be done during the event loop void analyze(const edm::EventBase& event);
private: /// input tag for mouns edm::InputTag muons_; edm::EDGetTokenT > muonsToken_; /// histograms std::map hists_; };
Note: When feeling unfamiliar with the code snippets above have a look to
WorkBookBasicCPlusPlus to learn more about the basics of C++, that you will regularly encounter when writing or reading code of EDAnalyzers. The class that you see above is derived from the abstract
edm::BasicAnalyzer class, which provides our class with the basic features to set up an EDAnalyzer of a FWLite executable within the CMS
EDM (Event Data Model), such that you can concentrate on the physics part of your work.
As for a normal EDAnalyzer you find a
beginJob(),
endJob() and a
analyze(...) function. These functions have to be provided with an implementation to make a concrete class out of the
edm::BasicAnalyzer class. In our example we also added an
edm::InputTag that we will use to pass the product label of the muon collection on to the analyzer code and a
std::map that we will use for histogram management. If you want to learn more about the
edm::BasicAnalyzer class have a look to the
WorkBookFWLiteExamples#ExampleFive.
Question 4 c):
What does it mean, that some parts of the declarations are private and others are public? What does private mean in C++?
You can find the implementation of the class in
PatExamples/src/PatMuonAnalyzer.cc
:
/// default constructor PatMuonAnalyzer::PatMuonAnalyzer(const edm::ParameterSet& cfg, TFileDirectory & fs): edm::BasicAnalyzer::BasicAnalyzer(cfg, fs), muons_(cfg.getParameter("muons")) { hists_["muonPt" ] = fs.make("muonPt" , "pt" , 100, 0., 300.); hists_["muonEta" ] = fs.make("muonEta" , "eta" , 100, -3., 3.); hists_["muonPhi" ] = fs.make("muonPhi" , "phi" , 100, -5., 5.); } PatMuonAnalyzer::PatMuonAnalyzer(const edm::ParameterSet& cfg, TFileDirectory & fs, edm::ConsumesCollector&& iC): edm::BasicAnalyzer::BasicAnalyzer(cfg, fs), muons_(cfg.getParameter("muons")) , muonsToken_(iC.consumes >(muons_)) { hists_["muonPt" ] = fs.make("muonPt" , "pt" , 100, 0., 300.); hists_["muonEta" ] = fs.make("muonEta" , "eta" , 100, -3., 3.); hists_["muonPhi" ] =fs.make("muonPhi" , "phi" , 100, -5., 5.); }
/// everything that needs to be done during the event loop void PatMuonAnalyzer::analyze(const edm::EventBase& event) { // define what muon you are using; this is necessary as FWLite is not // capable of reading edm::Views using pat::Muon;
// Handle to the muon collection edm::Handle<Muon> > muons; event.getByLabel(muons_, muons);
// loop muon collection and fill histograms for(std::vector<Muon>::const_iterator mu1=muons->begin(); mu1!=muons->end(); ++mu1){ hists_["muonPt" ]->Fill( mu1->pt () ); hists_["muonEta"]-> Fill( mu1->eta() ); hists_["muonPhi"]-> Fill( mu1->phi() ); }
Note: In the constructor the muon collection is passed on as a parameter. This gives you the possibility to analyze different muon collection with the same piece of code. Then we book a small set of histograms that we want to fill with some basic quantities. These quantities are
pt,
eta and
phi of each reconstructed muon in the analyzed data. We add these histograms to the
std::map that we have booked in the declaration of the class and register them to the TFileService. This is an
EDM service to facilitate your histogram management. Have a look to
SWGuideTFileService to learn more about it. The combination of the TFileService together with the declaration of the
std::map to manage the access of the histograms within our class is a very convenient way to perform your histogram management. Just add a line to the constructor if you want to add a histogram and fill it in the
analyze(...) function. Thus you only have to edit the implementation.
In the
analyze(...) function the muon collection is drawn into the event using the
edm::Handle. Within the
EDM this is always done the same way. Also the following loop over the muons is a typical piece of code that you will always find back when looping an object collection within the
EDM. We fill the booked histograms for all muons in the collection for each event.
Question 4 d):
You can view the edm::InputTag as a kind of string that keeps the module label of a collection in the event content. But it keeps more information. How would you look for the data members and member functions of the edm::InputTag class to find out what extra information it keeps? Have a look to the WorkBookPATDocNavigationExercise documentation for some hints.
In
PatExamples/plugins/PatMuonEDAnalyzer.cc
you can find the piece of code that 'wraps' our class implementation into a full EDAnaylzer plugin that can be used with
cmsRun:
#include "FWCore/Framework/interface/MakerMacros.h"
/* This is an example of using the PatMuonAnalyzer class to do a simple analysis of muons using the full framework and cmsRun. You can find the example to use this code in PhysicsTools /PatExamples/test/.... */ #include "PhysicsTools/UtilAlgos/interface/EDAnalyzerWrapper.h" #include "PhysicsTools/PatExamples/interface/PatMuonAnalyzer.h"
typedef edm::AnalyzerWrapper<PatMuonAnalyzer> PatMuonEDAnalyzer; DEFINE_FWK_MODULE(PatMuonEDAnalyzer);
Note: You can take this as a template of for any other 'wrap-up' of a class that has been derived from the
edm::BasicAnalyzer. You can use it for 90% of your analysis purposes. In case you need the
edm::EventSetup though you will have to fall back on the implementation of a full EDAnalyzer. You can find a full description how to do this on
WorkBookWriteFrameworkModule.
In
PatExamples/bin/PatMuonFWLiteAnalyzer
you can find the piece of code that 'wraps' our class implementation into a FWLite executable
int main(int argc, char* argv[]) { // load framework libraries gSystem->Load( "libFWCoreFWLite" ); AutoLibraryLoader::enable();
// only allow one argument for this simple example which should be the // the python cfg file if ( argc < 2 ) { std::cout << "Usage : " << argv[0] << " [parameters.py]" << std::endl; return 0; } if( !edm::readPSetsFrom(argv[1])->existsAs("process") ){ std::cout << " ERROR: ParametersSet 'plot' is missing in your configuration file" << std::endl; exit(0); }
PatMuonFWLiteAnalyzer ana(edm::readPSetsFrom(argv[1])->getParameter("process"), std::string("patMuonAnalyzer"), std::string("patMuonAnalyzer")); ana.beginJob(); ana.analyze(); ana.endJob(); return 0; }
To make sure that the executable is compiled we had to add a corresponding line to the
BuildFile.xml in the
bins directory of the package:
<use name="root"/>
<use name="boost"/>
<use name="rootcintex"/>
<use name="FWCore/FWLite"/>
<use name="DataFormats/FWLite"/>
<use name="FWCore/PythonParameterSet"/>
<use name="DataFormats/PatCandidates"/>
<use name="CommonTools/Utils"/>
<use name="PhysicsTools/FWLite"/>
<use name="PhysicsTools/Utilities"/>
<use name="PhysicsTools/PatUtils"/>
<use name="PhysicsTools/PatExamples"/>
<use name="PhysicsTools/SelectorUtils"/>
<environment>
<bin file="PatMuonEDMAnalyzer.cc"></bin>
<bin file="PatMuonFWLiteAnalyzer.cc"></bin>
<bin file="PatBasicFWLiteAnalyzer.cc"></bin>
<bin file="PatBasicFWLiteJetAnalyzer.cc"></bin>
<bin file="PatBasicFWLiteJetAnalyzer_Selector.cc"></bin>
<bin file="PatBasicFWLiteJetUnitTest.cc"></bin>
<bin file="PatCleaningExercise.cc"></bin>
<bin file="PatAnalysisTasksExercise.cc"></bin>
</environment>
The line
is the line in question here.
Note: You see the implementation of a normal C++ main function. The function
edm::readPSetsFrom(...) allows to read
edm::ParameterSets from configuration files similar to the
cfi files in the full framework. We instantiate the
PatMuonFWLiteAnalyzer, passing on the
edm::ParameterSet, the name of the
edm::ParameterSet that will hold the parameters that will be passed on to the executable and the name of the directory, in which the histograms are to be saved. If the last argument is left empty the histograms will be saved directly in thto the head of the histogram root. The configuration that we use, will give a similar output as you get it for the plugin version described above. If you want to learn more about the implementation of FWLite executables have a look to
WorkBookFWLiteExamples.
Question 4 e):
How would you add a statement to compile another executable with name MyPatExecutable.cc to this BuildFile.xml file?
How to access information from a pat::Candidate via an EDM-Tuple
You can also create an
EDM-Tuple from
pat::Candidates which you can easily and intuitively access again via the member functions of FWLite or just via plain root. The AT (Analysis Tools) group provides you with the tools to create flat n-tuples that automatically keep the event provenance information (as required by the CMS Physics management for any CMS publication) without having to write any line of C++ code! We also give guideline if you still want to write you own n-tupleizers. To learn more about these tools have a look to
SWGuideEDMNtuples. We are making use of a generic n-tuple dumper as described
here. The following configuration file shows how to create an
EDM-tuple from the
patTuple.root that we have created
above.
import FWCore.ParameterSet.Config as cms
process = cms.Process("Test")
process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( "file:patTuple_standard.root" ) ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )
process.MessageLogger = cms.Service("MessageLogger")
## --- ## This is an example of the use of the plain edm::Tuple dumper to analyze pat::Muons process.patMuonAnalyzer = cms.EDProducer( "CandViewNtpProducer", src = cms.InputTag("selectedPatMuons"), lazyParser = cms.untracked.bool(True), prefix = cms.untracked.string(""), eventInfo = cms.untracked.bool(True), variables = cms.VPSet( cms.PSet( tag = cms.untracked.string("pt"), quantity = cms.untracked.string("pt") ), cms.PSet( tag = cms.untracked.string("eta"), quantity = cms.untracked.string("eta") ), cms.PSet( tag = cms.untracked.string("phi"), quantity = cms.untracked.string("phi") ), ) )
process.p = cms.Path(process.patMuonAnalyzer)
process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string('edmTuple.root'), # save only events passing the full path SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('p') ), # save PAT Layer 1 output; you need a '*' to # unpack the list of commands 'patEventContent' outputCommands = cms.untracked.vstring('drop *', 'keep *_patMuonAnalyzer_*_*') )
process.outpath = cms.EndPath(process.out)
Note: We name the instance of the
CandViewNtpProducer patMuonAnalyzer as in the examples before. We create three flat TTrees from the
cleanPatMuon collection, from the
pt,
eta and
phi of the each muon. You can easily run a selection based on the StringCutParser beforehand. You can learn more about the StringCutParser on
SWGuidePhysicsCutParser. Finally we configure an output module for which we drop all other informatino but the three flat trees, that have produced with the
patMuonAnalyzer moduie. The output will be written into an
EDM file with name
edmTuple.root. To run this example do the following
cmsRun PhysicsTools/PatExamples/test/analyzePatMuons_tuple1_cfg.py
The content of the
edmTuple.root file is shown below:
Type Module Label Process
-----------------------------------------------------------------
vector<float> "patMuonAnalyzer" "eta" "PAT"
vector<float> "patMuonAnalyzer" "phi" "PAT"
vector<float> "patMuonAnalyzer" "pt" "PAT"
unsigned int "patMuonAnalyzer" "EventNumber" "PAT"
unsigned int "patMuonAnalyzer" "LumiBlock" "PAT"
unsigned int "patMuonAnalyzer" "RunNumber" "PAT"
Note: As you see apart from
pt,
eta and
phi also the
EventNumber,
LumiBlock and
RunNumber of each event are written into the tuple per default. This file contains the typical structure of an
EDM file. You can investigate it and find the TTrees in the
Events folder. You can also access the flat tuples making use of the features of FWLite. An example for a compiled executable is given below:
int main(int argc, char* argv[]) { // ---------------------------------------------------------------------- // First Part: // // * enable the AutoLibraryLoader // * book the histograms of interest // * open the input file // ----------------------------------------------------------------------
// load framework libraries gSystem->Load( "libFWCoreFWLite" ); AutoLibraryLoader::enable();
// initialize command line parser optutl::CommandLineParser parser ("Analyze FWLite Histograms");
// set defaults parser.integerValue ("maxEvents" ) = 1000; parser.integerValue ("outputEvery") = 10; parser.stringValue ("outputFile" ) = "analyzeEdmTuple.root";
// parse arguments parser.parseArguments (argc, argv); int maxEvents_ = parser.integerValue("maxEvents"); unsigned int outputEvery_ = parser.integerValue("outputEvery"); std::string outputFile_ = parser.stringValue("outputFile"); std::vector inputFiles_ = parser.stringVector("inputFiles");
// book a set of histograms fwlite::TFileService fs = fwlite::TFileService(outputFile_.c_str()); TFileDirectory dir = fs.mkdir("analyzePatMuon"); TH1F* muonPt_ = dir.make("muonPt" , "pt" , 100, 0., 300.); TH1F* muonEta_ = dir.make("muonEta" , "eta" , 100, -3., 3.); TH1F* muonPhi_ = dir.make("muonPhi" , "phi" , 100, -5., 5.);
// loop the events int ievt=0; for(unsigned int iFile=0; iFile<inputFiles_.size(); ++iFile){ // open input file (can be located on castor) TFile* inFile = TFile::Open(inputFiles_[iFile].c_str()); if( inFile ){ // ---------------------------------------------------------------------- // Second Part: // // * loop the events in the input file // * receive the collections of interest via fwlite::Handle // * fill the histograms // * after the loop close the input file // ---------------------------------------------------------------------- fwlite::Event ev(inFile); for(ev.toBegin(); !ev.atEnd(); ++ev, ++ievt){ edm::EventBase const & event = ev; // break loop if maximal number of events is reached if(maxEvents_>0 ? ievt+1>maxEvents_ : false) break; // simple event counter if(outputEvery_!=0 ? (ievt>0 && ievt%outputEvery_==0) : false) std::cout << " processing event: " << ievt << std::endl;
// Handle to the muon pt edm::Handle<float> > muonPt; event.getByLabel(std::string("patMuonAnalyzer:pt"), muonPt); // loop muon collection and fill histograms for(std::vector<float>::const_iterator mu1=muonPt->begin(); mu1!=muonPt->end(); ++mu1){ muonPt_ ->Fill( *mu1 ); } // Handle to the muon eta edm::Handle<float> > muonEta; event.getByLabel(std::string("patMuonAnalyzer:eta"), muonEta); for(std::vector<float>::const_iterator mu1=muonEta->begin(); mu1!=muonEta->end(); ++mu1){ muonEta_ ->Fill( *mu1 ); } // Handle to the muon phi edm::Handle<float> > muonPhi; event.getByLabel(std::string("patMuonAnalyzer:phi"), muonPhi); for(std::vector<float>::const_iterator mu1=muonPhi->begin(); mu1!=muonPhi->end(); ++mu1){ muonPhi_ ->Fill( *mu1 ); } } // close input file inFile->Close(); } // break loop if maximal number of events is reached: // this has to be done twice to stop the file loop as well if(maxEvents_>0 ? ievt+1>maxEvents_ : false) break; } return 0; }
Note: You can find the full example in
PhysicsTools/PatExamples/bin/PatMuonEDMAnalyzer.cc
. It follows the implementation of a typical compiled FWLite example as described in
WorkBookFWLiteExamples. You can run the example as follows:
PatMuonEDMAnalyzer inputFiles=edmTuple.root outputFile=analyzePatMuons.root
Have a look into the implementation of the executable to find out what you have to expect as output. After the explanations above it should be easy for you to figure it out.
Note: It is not necessary to produce the
EDM-tuple from a persistent set of
pat::Canddiate, a PAT tuple. You can create
pat::Candidates 'on the fly' without making them persistent. An example for such an
EDM -tuple directly from a RECO file without making the
pat::Candidate collections persistent is given below:
## import skeleton process from PhysicsTools.PatAlgos.patTemplate_cfg import *
## --- ## This is an example of the use of the plain edm::Tuple dumper to analyze pat::Muons process.patMuonAnalyzer = cms.EDProducer( "CandViewNtpProducer", src = cms.InputTag("selectedPatMuons"), lazyParser = cms.untracked.bool(True), prefix = cms.untracked.string(""), eventInfo = cms.untracked.bool(True), variables = cms.VPSet( cms.PSet( tag = cms.untracked.string("pt"), quantity = cms.untracked.string("pt") ), cms.PSet( tag = cms.untracked.string("eta"), quantity = cms.untracked.string("eta") ), cms.PSet( tag = cms.untracked.string("phi"), quantity = cms.untracked.string("phi") ), ) )
## let it run process.p = cms.Path( process.patDefaultSequence * process.patMuonAnalyzer )
process.out.fileName = "edmTuple.root" process.out.outputCommands = ['drop *', 'keep *_patMuonAnalyzer_*_*']
Exercises
Before leaving this page try to do the following exercises:
Exercise 4a): Write your own MyPatJetAnalyzer following the example of the PatMuonAnalyzer above. Choose the implementation as a (full framework) EDAnalyzer. Read in PAT jets and electrons and answer the following questions:
What is the mean pt of the leading jet?
What is the mean of the closest distance (in deltaR) between the leading electron and the closest pat default jet above 30GeV?
Note: Do you still remember the jet algorithm that you are using? To what jet energy correction (JEC) level is this jet corrected? What is the way to find out?
Exercise 4 b): Move the definition of the PatJetEDAnalyzer module from the configuration (
cfg) file in the
test directory to a
cfi file in the python directory. Import the module and create two clones of it in your
cfg file. Then import the
jetSelector_cfi
module from the
selectionLayer1
directory of the
PatAlgos
package and create a collection of jets with a
pt larger than 60
GeV. Replace the default input for the jet collection of one of the analyzer clones by this new collection. Now answer the following questions:

What is the mean jet multiplicity of all jets and of all high pt jets?

What is the difference in eta of all jets and of all high pt jets?
Note: The following links might be of help for you:
Exercise 4 c): Extend the PatMuonAnalyzer class by the UserVariable
relIso as defined in
Exercise 2d) in
Exercise 2. Have a look to
SWGuidePATUserData to learn how to read this information from the
pat::Muons. Fill a histogram with 50 bins from 0. to 100. Run over the ttbar RelVal input sample, that is used from the
patTuple_standard_cfg.py file.
What is the mean of this variable?
Exercise 4 d): Create an
EDM-tuple with PAT on the fly as described on this TWiki, by a customized
patTuple_standard_cfg.py
.
Exercise 4 e): In the above example we made use of the BasicAnalyzer base class. It shows that, when restricted to the abilities of FWLite the full framework and FWLite are literally the same. Have a look to
WorkBookFWLiteExamples#ExampleFive to learn more about this. Investigate the necessary file in the
PhysicsTools/PatUtils
package and try to understand how the
FWLiteAnalyzerWrapper and the
EDAnalyzerWrapper work.
In case of problems don't hesitate to contact the
SWGuidePAT#Support. Having successfully finished
Exercise 4 you are well prepared to do an analysis using PAT.
CONGRATULATIONS! 
. You might still want to proceed to other exercises of the
WorkBookPATTutorial to go deeper into the material and to learn more about the many possibilities to configure and customise your personal
pat::Tuple. #ReviewStatus
Review status