WORKBOOK - SLAC National Accelerator Laboratory...Prepare your account and computer •Set up your...

46
WORKBOOK for NEW BABARIANS CHIH-HSIANG CHENG / CALTECH BABAR ANALYSIS SCHOOL, 10/25/2009

Transcript of WORKBOOK - SLAC National Accelerator Laboratory...Prepare your account and computer •Set up your...

WORKBOOKfor

NEW BABARIANS

CHIH-HSIANG CHENG / CALTECH

BABAR ANALYSIS SCHOOL, 10/25/2009

Today’s goals• Introduction to BABAR off-line software.‣ Where is the code?‣ How is it managed?‣ How is it structured?

• Get a taste of what is it like to analyze BABAR data‣ How do I set up my work space?‣ How do I get the data?‣ What do I have to work with?‣ How do I do simulation?‣ How do I run the jobs?‣ Make some plots.‣ Someone must have written many software tools

for me to use, right?‣ How do I add my code to BABAR software?‣ How do I debug?‣ Where can I ask questions (and get answers

efficiently without looking like an idiot)?

2

Prepare your account and computer• Set up your SLAC account• Secure shell (ssh) is required to connect to

SLAC.• Use public Redhat Enterprise Linux or

Scientific Linux 3/4

‣ They will take you to a computer (names noric or yakut or something else) with lower load.

• Check your status: (chkuser <userid>)• Do I have proper environment variables?

• X window to display plots on your screen.4

UNIXID - Prints unix userid if it exists at SLAC BFACT - User is/is not a member of the Unix group 'bfactory' (needed for NFS space where Objectivity stores data). AFS - User does/does not have a SLAC AFS account BBR_COMM - User is/is not a member of the BBR_COMMUNITY (an AFS accesslist) OBJECTIVITY - User has/has not signed the Objectivity agreement.

ssh -X [email protected] rhel3-32 sl4-32 sl3-32 More on public machines

Code management• Software is organized in “releases”. In

BABAR, they are labeled with three digits, e.g., 24.3.5.‣ We increment first digit after major

developments, and the last digit after minor development or bug fix.

‣ Each release contains hundreds of packages.‣ Each package is intended to perform a well-

defined task.• You can find code under $BFROOT/dist (=

$BFDIST)‣ However, do not copy code from there. Real

code is managed by SRT and CVS.• A release is built periodically for several

types of computer architectures. All libraries are compiled and many binary executables are linked (e.g., reconstruction, simulation production, utilities)‣ More than 99% of the code won’t be touched by

you as an analyst. You don’t event have to look at them.

5

and many more packages

$BFROOT/dist/packages -> packages -> versions -> package files$BFROOT/dist/releases -> releases -> packages -> package files

Prepare your work space• Make sure you have enough disk space• Your account is on AFS, which you don’t get

much space. The library and executable you build will be in a scratch “build space”. The large output should be in yet another place.

• Let’s make a directory for the test release:• And then create a build space:‣ Build area is also on AFS. Not intended for data

storage. Contents will be deleted 7 days after creation.

• Find a temporary output storage:‣ Scratch area is on NFS. Contents will also be

deleted after 7 days. You need to move the output to somewhere else afterwards. Consult your analysis working group for a longer term storage area.

6

% mkdir babar/BAS% cd babar/BAS

% bbrCreateBuildArea% ls $BFROOT/build/<first_letter>/<my_id>

% mkdir -p $BFROOT/work/<first_letter>/<my_id>

From now on, the user id used in the examples will be “myslacid”. So the above example will beBFROOT/work/m/myslacid/

Set up my first release• newrel, srtpath, and addpkg‣ part of software release tools (SRT) commands‣ new release

‣ set up SRT path

‣ Set up conditions database

7

% cd babar/BAS% newrel -t -s $BFROOT/build/m/myslacid analysis-51 bas-a51-1

build area nickname of release 24.3.6

the given name (by you) of the directory

% cd bas-a51-1% srtpath [enter] [enter]

newrel version: 1.16 GNU Make version 3.79.1,Build OPTIONS = Linux26SL4_i386_gcc346-Debug-native-Optimize-Fastbuild-Ldlink2-SkipSlaclog-Static-LstaticLinux yakut12 2.6.9-89.0.11.ELsmp #1 SMP Tue Sep 15 13:12:01 CDT 2009 i686 athlon i386 GNU/Linux [uname -a][Warning]: ./bin/Linux26SL4_i386_gcc346 (and/or) /afs/slac.stanford.edu/g/babar/dist/releases/24.3.6/bin/Linux26SL4_i386_gcc346 is not in PATH, type 'srtpath' to fix PATH.-> installdirs:test does not exist, remake itbin/Linux26SL4_i386_gcc346 does not exist, remake it... ...... ...Creating database/GNUmakefile from release 24.3.6next, addpkg, checkout or ln -s to your packages, then gmake installdirs remember to run srtpath. (see man page of srtpath about setting it up)

enter release number (CR=24.3.6):

Select/enter BFARCH (CR=1):1) Linux26SL4_i386_gcc346 [prod][test][active][default]2) Linux26SL4_i386_gcc346-noOptimize-Debug [prod]3) Linux24SL3_i386_gcc323 [prod]4) Linux24SL3_i386_gcc323-Optimize-Profile [prod]5) Linux24SL3_i386_gcc323-noOptimize-Debug [prod]

% cond24boot09Setting CDB_ROO_BOOT to kanga::/cond24boot09/full/cdb_boot.root

Setting CDB_ROO_BOOT to kanga::/cond24boot09/full/cdb_boot.root

Add workdir package• First, take a look what’s in your release‣ bin, lib, shlib are linked to your build area

• workdir is a special package. You should always run your jobs from workdir.‣ addpkg invokes cvs co to check out a certain

version of workdir package.‣ gmake workdir.setup to set up a few soft links- PARENT points to the central BABAR release area- RELEASE points to your release (the parent

directory of workdir)

• We can already run some stuff with these. Let’s try it.

8

% ls -ltotal 89-rw-r--r-- 1 myslacid br 71459 Oct 20 14:02 GNUmakefilelrwxr-xr-x 1 myslacid br 60 Oct 20 14:02 bin -> /afs/slac.stanford.edu/g/babar/build/m/myslacid/bas-a51-1/bin/drwxr-xr-x 2 myslacid br 2048 Oct 20 14:02 database/drwxr-xr-x 2 myslacid br 2048 Oct 20 14:02 doc/drwxr-xr-x 2 myslacid br 2048 Oct 20 14:02 include/lrwxr-xr-x 1 myslacid br 60 Oct 20 14:02 lib -> /afs/slac.stanford.edu/g/babar/build/m/myslacid/bas-a51-1/lib/drwxr-xr-x 3 myslacid br 2048 Oct 20 14:02 man/drwxr-xr-x 2 myslacid br 2048 Oct 20 14:02 results/lrwxr-xr-x 1 myslacid br 62 Oct 20 14:02 shlib -> /afs/slac.stanford.edu/g/babar/build/m/myslacid/bas-a51-1/shlib/drwxr-xr-x 2 myslacid br 2048 Oct 20 14:02 shtmp/drwxr-xr-x 3 myslacid br 2048 Oct 20 14:02 test/drwxr-xr-x 2 myslacid br 2048 Oct 20 14:02 tmp/

% addpkg workdirOffline Release 24.3.6 uses workdir version V00-04-21, will check that outcvs checkout: Updating workdirU workdir/.cvsignoreU workdir/.rootrcU workdir/GNUmakefile......

% gmake workdir.setup

PARENT -> /afs/slac.stanford.edu/g/babar/dist/releases/24.3.6/RELEASE -> ..//bin -> RELEASE/bin/shlib -> RELEASE/shlib/

Now let’s do something with this test release we just created - Generate some simulation data

9

Monte Carlo Simulation in a nutshell

10

Data Collections(same format as data, except we know the

“truth” in MC)

electronics digitization

Material interaction

Physics events are generated from interaction matrix elements. You can create your physics events however you want.

We are going to run this in a minute

Decay file• EvtGen reads text-based decay files to decide

how particles should decay. If not specified otherwise, the decays follows DECAY.DEC in EvtGen package.

• Tens of thousands of customized decay files are in ProdDecayFiles package. Let’s take a look at one of them.

11

% less PARENT/EvtGen/DECAY.DEC

Take a look, from workdir

It first defines many parameters, and then for each known particles, it specifies the decay products, branching fractions and interaction models, many based on PDG, others based on educated guess.

#################################################################### ## Decay: B0 -> D*- pi+ (D*- -> anti-D0 pi- (anti-D0 -> K+ pi-)) ## anti-B0 -> X; + cc ## ## Author: Giampiero Mancinelli ## Date: 03/09/2001 #####################################################################Alias MyB0 B0Alias Myanti-B0 anti-B0Alias MyD*+ D*+Alias MyD*- D*-Alias MyD0 D0Alias Myanti-D0 anti-D0#Decay Upsilon(4S)1.000 B0 anti-B0 MyB0 Myanti-B0 VSS_BMIX dm;Enddecay#Decay Myanti-B01.000 MyD*+ pi- PHSP;Enddecay

Decay MyB01.000 MyD*- pi+ PHSP;Enddecay#Decay MyD*+1.000 MyD0 pi+ VSS;Enddecay#Decay MyD*-1.000 Myanti-D0 pi- VSS;Enddecay#Decay MyD01.000 K- pi+ PHSP;Enddecay#Decay Myanti-D01.000 K+ pi- PHSP;Enddecay#End

% less PARENT/ProdDecayFiles/B0B0bar_Dstarpi_Dstar-D0pi_D0-Kpi.dec

Tcl, run time job control• A job is controled by a tcl snippet:‣ An example of tcl snippet for MooseApp

• Before we start, we need to create a directory for output collections.

• Take a peek at Moose/MooseProduction.tcl‣ It defines many configuration variables and

sources many other tcl files to set up the production sequences and path.

12

set ProdTclOnly trueset RUNNUM 987655set CONDALIAS Aug2001set SimAppBkndInputCollection /store/SP/BkgTriggers/BkgTriggers_200108_V01set SimAppBkndFirstEvent 1set SimAppDigiMix trueset SimAppKanDigiMix trueset NEVENT 100set UDECAY PARENT/ProdDecayFiles/B0B0bar_Dstarpi_Dstar-D0pi_D0-Kpi.decset MooseHBookFile myMoose.hbookset MooseOutputCollection /work/users/myslacid/BAS/moose-dstarpisourceFoundFile Moose/MooseProduction.tcl

% less moose-dstarpi.tclYou can copy it to your workdir:% cp ~chcheng/babar/BAS/bas-a51-1/workdir/moose-dstarpi.tcl .

sets the random number seedsets the detector conditionsmachine/detector background collection

number of events to generatethe decay fileQA histogramsoutput collectionsource the body of the production tcl

link to more tcl info

Change this to your id

% KanUserAdmin createuserCreating /work/users/myslacid area...

See where to write user collections

% less PARENT/Moose/MooseProduction.tcl

Running Moose• Moose is built in every release already:

• Submit a job to a batch queue:

• Check the job status:‣ bjobs -l for the long version

• Peek at the log file:• When done, check the log file• Check the output collection:‣ For more instructions:- KanUserAmdin help- KanCollUtil -h

13

% which MooseApp/afs/slac.stanford.edu/g/babar/dist/releases/24.3.6/bin/Linux26SL4_i386_gcc346/MooseApp

% bsub -q kanga -o $BFROOT/work/m/myslacid/BAS/moose-dstarpi.log MooseApp moose-dstarpi.tcl

% bjobsJOBID USER STAT QUEUE FROM_HOST EXEC_HOST JOB_NAME SUBMIT_TIME508749 chcheng RUN kanga yakut12 fell0251 *tarpi.tcl Oct 20 16:18

% bpeek [jobid]

% KanUserAdmin list /work/users/myslacid/BAS/work/users/myslacid/BAS/moose-dstarpi

% KanCollUtil /work/users/myslacid/BAS/moose-dstarpi/work/users/myslacid/BAS/moose-dstarpi (100 events)

% KanCollUtil -P /work/users/myslacid/BAS/moose-dstarpi/work/users/myslacid/BAS/moose-dstarpi (100 events) PFN 000 /nfs/sulky40/user01//work/users/myslacid/BAS/moose-dstarpi.01.root PFN 001 /nfs/sulky40/user01//work/users/myslacid/BAS/moose-dstarpi.02E.root

Batch queue for running jobs with BABAR event collections

Working towards analysis jobs

14

Framework and modules• Babar code is built from objects called

modules. Each module uses the data to to perform one well-defined task. (input, output, fit tracks, make clusters, build decay tree, make histograms, etc.)

• The modules are strung together into an ordered analysis path (configured by tcl). Whenever you run an analysis job, your application creates ("instatiates") an object called the Framework. The Framework passes data from module to module, until it reaches the last module of the analysis path.

• Each module has beginJob(), endJob() and event().

• Let’s run MooseApp without any argument to get into the framework and list all the modules MooseApp knows.

15

See more detail, click here

% MooseApp> mod list...> q

Framwork is existing now.

Skim in one page• Skim is a process of selecting a subset of the

data with very loose criteria and creating standard event store collections for later process and analysis.

• More than a hundred of skims are done by central production at each skim cycle.

• Skim consists of a set of filter modules that decide which events will proceed to the end and be written to output event store.

• One can also do his/her own skim if none of the centrally produced skims are suitable for his/her analysis, or if you want to further reduce the skim size, and/or if you want to add user data or persistent composite candidates.‣ This is a more advanced topic. We won’t go

further today. Most of the time, centrally produced skims are good enough.

16

Click the picture to go to the page

Click the picture to go to the page

My first analysis job• For the next few minutes we will‣ Check out BetaMiniUser (an example user

analysis package).‣ Add a simple module to BetaMiniUser.‣ Build a user executable.‣ Set up the tcl script and run a job to make simple

histograms.

• Examine GNUMakefile for the moment

17

% addpkg BetaMiniUseroffline Release 24.3.6 uses BetaMiniUser version V00-04-05, will check that outcvs checkout: Updating BetaMiniUserU BetaMiniUser/.cvsignoreU BetaMiniUser/AppUserBuild.cc...

Go back to the release directory (parent of workdir)

Copy a few files from my directory to your BetaMiniUser directory for today’s first example% cp ~chcheng/babar/BAS/bas-a51-1/BetaMiniUser/MomentumSpectrum* BetaMiniUser/

Build the library

% bsub -q bldrecoq -o log1 gmake lib

% less GNUMakefile...BINS := BetaMiniAppBINCCFILES := AppUserBuild.cc AppUserBuildBase.cc...

Special batch queue for building

name of the executable files that pulls together and link all the modules

AppUserBuildBase.cc• Edit this file: add our module and comment

out modules we don’t need.

18

#include "BaBar/BaBar.hh"

//-----------------------// This Class's Header --//-----------------------#include "BetaMiniUser/AppUserBuildBase.hh"

//-------------------------------// Collaborating Class Headers --//-------------------------------#include "BetaMiniQA/BetaMiniQaSequence.hh"#include "BetaMiniUser/MyDstarAnalysis.hh"#include "BetaMiniUser/MyK0Analysis.hh"#include "BetaMiniUser/MyMiniAnalysis.hh"#include "BetaMiniUser/MyReadList.hh"#include "BetaMiniUser/MyTimePointAnalysis.hh"#include "BetaMiniUser/BetaMiniBackgroundFrameCounter.hh"#include "BetaMiniSequences/BetaMiniActions.hh"#include "BetaMiniSequences/BetaMiniPhysicsSequence.hh"#include "BetaMiniSequences/BetaMiniSequence.hh"#include "BetaMiniSequences/BetaMiniWriteSequence.hh"#include "BetaPid/PidPionMicroSequence.hh"#include "Framework/AppFramework.hh"#include "Framework/AppUserBuild.hh"#include "TagModules/TagInspector.hh"#include "UsrTools/UsrMakerTools.hh" #include "BetaMiniUser/MomentumSpectrum.hh" void AppUserBuildBase(AppUserBuild* theBuild, AppFramework* theFramework)

{ //Core sequence BetaMiniSequence(theBuild);

BetaMiniActions(theFramework); BetaMiniQaSequence(theBuild); BetaMiniPhysicsSequence(theBuild); //Reskimming sequences and modules ( De Nardo May 12 2004 ) BetaMiniWriteSequence(theBuild); UsrMakerTools(theBuild); // add modules for writing user data //Analysis modules// theBuild->add(new MyMiniAnalysis("MyMiniAnalysis", "MyMiniAnalysis"));// theBuild->add(new MyDstarAnalysis("MyDstarAnalysis", "Dstar analysis module"));// theBuild->add(new MyK0Analysis( "MyK0Analysis", "K0 analysis module"));

// PidPionMicroSequence(theBuild); // theBuild->add(new MyTimePointAnalysis());// theBuild->add(new BetaMiniBackgroundFrameCounter());// theBuild->add (new TagInspector("TagInspector","A module to histogram tag bits"));// theBuild->add (new MyReadList("MyReadList", "read a list of composite candidates"));

theBuild->add( new MomentumSpectrum("MomentumSpectrum", "Make track momentum histogram"));

}

Add

Comment out

Link and run• Link and run a job

• A root file is created:

• Draw histograms:

19

% bsub -q bldrecoq -o log1 gmake BetaMiniUser.bin

% cd workdir% BetaMiniApp ../BetaMiniUser/MomentumSpectrum.snip.tcl |& tee momentum.log

% ls -1 *.root-rw-r--r-- 1 chcheng eb 10448 Oct 21 13:55 momentum.root

% bbrroot -l momentum.rootroot [0] Attaching file momentum.root as _file0...root [1] .lsTFile** momentum.root Created for you by RooTupleManager TFile* momentum.root Created for you by RooTupleManager KEY: TH1F h1d1;1 Cherenkov angle ... ... KEY: TH1F h1d20;1 Reco track momentum KEY: TH1F h1d21;1 Reco-mc track momentum diff.

root [2] h1d20->Draw()<TCanvas::MakeDefCanvas>: created default TCanvas with name c1root [3] h1d21->Draw()root [4] .q

This is the end of ROOT -- Goodbye

What have we done?• Tcl snippet

• Main tcl

20

% cat ../BetaMiniUser/MomentumSpectrum.snip.tcllappend inputList /work/users/chcheng/BAS/moose-dstarpiset NEvent 100set histFileName momentum.rootsourceFoundFile BetaMiniUser/MomentumSpectrum.tcl

% cat ../BetaMiniUser/MomentumSpectrum.tcl# always source the error logger early in your main tcl scriptsourceFoundFile ErrLogger/ErrLog.tclsourceFoundFile FrameScripts/FwkCfgVar.tclsourceFoundFile FrameScripts/talkto.tcl

# Disable the use of envvarsset ProdTclOnly true

# set the error logging level to 'warning'. If you encounter a configuration # error you can get more information using 'trace'ErrLoggingLevel warning

## allowed (non-expert) values of levelOfDetail are "micro", "cache", "extend" ## or "refit"FwkCfgVar levelOfDetail "cache"

## allowed values of ConfigPatch are "Run1", "Run2" or "MC". This MUST be set ## consistent ## with your input data type or you will get INCONSISTENT OR ## INCORRECT RESULTSFwkCfgVar ConfigPatch "MC"

## Set the number of events to runFwkCfgVar NEvent

## choose the flavor of ntuple to write (hbook or root) and the file nameFwkCfgVar BetaMiniTuple "root"FwkCfgVar histFileName "MyMiniAnalysis.root"

## create Everything path and add core sequences to it.## the very basicsourceFoundFile BetaMiniUser/btaMini.tcl## some more physics stuff# sourceFoundFile BetaMiniUser/btaMiniPhysics.tcl## everything under the sun#sourceFoundFile BetaMiniUser/btaMiniPhysProdSequence.tcl

## Add our Analysis modulepath append Everything MomentumSpectrum## Show the entire pathpath list## Start the jobif [info exists NEvent] { ev begin -nev $NEvent} else { ev begin}

ErrMsg trace "completed OK"exit

Declare framwork configuration variable and its default value

What’s in my path?• Take a look at the log file:

21

Everything (enabled) BetaMiniSequence (enabled) BetaMiniInitSequence (enabled) BetaMiniEnvSequence (enabled) RecEventControlSequence (enabled) RecCallgrindControl (enabled) turn callgrind on or off EvtCounter (enabled) event counter RecTimeStampFilter (enabled) timestamp filter RecThreadSafety (enabled) Initialize HepMatrix thread safety GenBuildEnv (enabled) Build General Environment ... ... [MODULES TO BUILD ENVIRONMENT] ... ... BetaMiniReadSequence (enabled) CdbEvtLoadStateIdHistory (enabled) CdbEvtLoadStateId clone KanCreateCM (enabled) Create KanConversionManager HdrKanLoadHdr (enabled) HdrKanLoad clone ... ... [MODULES TO LOAD DATA] ... ... BetaMiniDetectorSequence (enabled) BetaMiniPidSequence (enabled) PidExpandChargedSummary (enabled) Expand PidChargedSummary to separate lists PidMakeTrkMap (enabled) Make and fill map from Tracks to PidInfo objects BetaMiniTrkSequence (enabled) KalFit (enabled) Kalmanize Mini tracks ... ... [DETECTOR SEQUENCES/MODULES] ... ...

output of path list

22

BetaMiniTruSequence (enabled) GTrkFillDaughters (enabled) Fill daughters field of GTracks BtaLoadMcCandidates (enabled) Load Default MC Beta Candidates BtaLoadGHitAssoc (enabled) Beta - MC GHit associator BetaMiniBtaSequence (enabled) BtaProdCreateSequence (enabled) BtaLoadEvtInfo (enabled) Load default EventInfo PhysInitEvent (enabled) Beta- event initialization PhysCreateAlias (enabled) create aliases for ALists BetaLoadMiniSequence (enabled) BtaLoadBeamSpot (enabled) load the BeamSpot into the EventInfo LoadMiniBtaCandidates (enabled) load Beta lists from mini objects LoadEventInfoSequence (enabled) BtaLoadBeamSpot (enabled) load the BeamSpot into the EventInfo BtaGoodTrackSequence (enabled) LoadBetaTracksLists (enabled) Create BetaCandidate Lists GoodTrackVeryLooseSelection (enabled) Selection of good track for primary vertex GoodTrackAccSelection (enabled) Selection of good track within acceptance GoodTrackLooseSelection (enabled) Selection of good track for primary vertex GoodTrackAccLooseSelection (enabled) Selection of good track within acceptance plus loose cuts GoodTrackTightSelection (enabled) Selection of good track for primary vertex GoodPhotonLooseSelection (enabled) Selection of loose good photons GoodNeutralLooseAccSelection (enabled) Selection of loose good photons GoodPhotonDefaultSelection (enabled) Selection of default good photons TrkMicroDispatch (enabled) Create bitmaps for tracks TrkEffTableCreator (disabled) Create tracking efficiency tables VtxEvent (enabled) search the vertex of the event BetaMiniUtilitySequence (enabled) CpuCheck (enabled) Check CPU time remaining Signal (enabled) intercept ^C PrintParms (disabled) print parameter values ReportFPE (enabled) handle and report floating point exceptions MomentumSpectrum (enabled) Make track momentum histogram

our analysis module

Header file of our module• You need to know a bit C++.

23

% cat ../BetaMiniUser/MomentumSepctrum.hh...#ifndef MOMENTUMSPECTRUM_HH#define MOMENTUMSPECTRUM_HH

//----------------------// Base Class Headers --//----------------------#include "Framework/AppModule.hh"

//------------------------------------// Collaborating Class Header files --//------------------------------------#include "AbsParm/AbsParmIfdStrKey.hh"#include "ProxyDict/IfdKey.hh"

//------------------------------------// Collaborating Class Declarations --//------------------------------------class HepHistogram;class HepTupleManager;// ---------------------// -- Class Interface --// --------------------- class MomentumSpectrum : public AppModule {

//--------------------// Instance Members --//--------------------

public:

// Constructors MomentumSpectrum( const char* const theName, const char* const theDescription ); // Destructor virtual ~MomentumSpectrum( ); // Operations virtual AppResult beginJob( AbsEvent* anEvent ); virtual AppResult event ( AbsEvent* anEvent ); virtual AppResult endJob ( AbsEvent* anEvent ); protected: // Parameters (interface with tcl) AbsParmIfdStrKey _btaMicroList; AbsParmIfdStrKey _btaTruthMap;

// define "local" variables to store from event to event HepTupleManager *_manager; HepHistogram *_hist1, *_hist2; bool _WarnUser;

private:

};

#endif

Main code of our module

24

% cat ../BetaMiniUser/MomentumSepctrum.cc...#include "BaBar/BaBar.hh"

//-----------------------// This Class's Header --//-----------------------#include "BetaMiniUser/MomentumSpectrum.hh"

//-------------------------------// Collaborating Class Headers --//-------------------------------#include "AbsEnv/AbsEnv.hh"#include "AbsEvent/AbsEvent.hh"#include "Beta/BtaCandidate.hh"#include "BetaCoreTools/BtaMcAssoc.hh"#include "CLHEP/Alist/AIterator.h"#include "ErrLogger/ErrLog.hh"#include "GenEnv/GenEnv.hh"#include "HepTuple/TupleManager.h"#include "HepTuple/Histogram.h"#include "ProxyDict/IfdStrKey.hh"#include "ProxyDict/Ifd.hh"

//----------------// Constructors --//----------------

// in general, a module constructor should not do much. The beginJob// member function is a better place to put initialization//// This ctor initializes the three sample list-name parametersMomentumSpectrum::MomentumSpectrum( const char* const theName, const char* const theDescription ) : AppModule( theName, theDescription ) , _btaMicroList( "btaMicroList", this, "ChargedTracks") , _btaTruthMap( "btaTruthMap", this, "GHit") , _hist1(0), _hist2(0) , _WarnUser(true){ commands()->append( &_btaMicroList ); commands()->append( &_btaTruthMap );}

//--------------// Destructor --//--------------MomentumSpectrum::~MomentumSpectrum( ){}

Default name

25

//--------------// Operations --//--------------

AppResultMomentumSpectrum::endJob( AbsEvent* anEvent ){ return AppResult::OK;}

// The begin(AppJob*) member function is run before any events are processedAppResultMomentumSpectrum::beginJob( AbsEvent* anEvent ){ // Names starting with underscores are defined in the // .hh file as class variables. They live for the // life of the analysis object (this one), so can be used to communicate // between the begin, event and end functions. HepTupleManager* _manager = gblEnv->getGen()->ntupleManager(); assert(_manager != 0); // book histograms _hist1 = _manager->histogram("Reco track momentum", 50, 0.0, 10.0); _hist2 = _manager->histogram("Reco-mc track momentum diff.", 50, -0.1, 0.1);

return AppResult::OK;}

AppResultMomentumSpectrum::event( AbsEvent* anEvent ){ // Get a list of BtaCandidate HepAList<BtaCandidate>* trkList= Ifd<HepAList< BtaCandidate > >::get(anEvent, _btaMicroList.value()); if ( !trkList ) { // Couldn't find the list. Abort!! ErrMsg(fatal) << "Could not locate list " << _btaMicroList.value() << ". This is likely to be a configuration error." << endmsg; }

// Get the default truth mapping BtaMcAssoc* truthMap = Ifd< BtaMcAssoc >::get(anEvent, _btaTruthMap.value()); if (truthMap == 0){ if (_WarnUser) { ErrMsg(warning) << "Could not locate truth map " << _btaTruthMap.value() << " in the event." << " (This message is printed only once)" << endmsg; _WarnUser = false; } }

// Iterate through the list HepAListIterator<BtaCandidate> iter(*trkList); while ( BtaCandidate *cand= iter() ) { // Fill the track momentum to an histogram _hist1->accumulate(cand->p());

// Get the truth partner if available if (truthMap) { const BtaCandidate *mc= truthMap->mcFromReco(cand); if ( mc ) { _hist2->accumulate(cand->p() - mc->p()); } } }

return AppResult::OK;}

Control the module parameter• Inspect the parameters

26

% BetaMiniApp > mod talk MomentumSpectrum

MomentumSpectrum> showCurrent value of item(s) in the "MomentumSpectrum" module:

Value of verbose for module MomentumSpectrum: f Value of production for module MomentumSpectrum: f Value of enableFrames for module MomentumSpectrum: f Value of btaMicroList for module MomentumSpectrum: IfdStrKey(ChargedTracks) Value of btaTruthMap for module MomentumSpectrum: IfdStrKey(GHit)

MomentumSpectrum> btaMicroList set GoodTracksLoose

MomentumSpectrum> showCurrent value of item(s) in the "MomentumSpectrum" module:

Value of verbose for module MomentumSpectrum: f Value of production for module MomentumSpectrum: f Value of enableFrames for module MomentumSpectrum: f Value of btaMicroList for module MomentumSpectrum: IfdStrKey(GoodTracksLoose) Value of btaTruthMap for module MomentumSpectrum: IfdStrKey(GHit)

MomentumSpectrum> exit> exitFramework is exiting now.

Do it in your tcl snip

% cat ../BetaMiniUser/MomentumSpectrum.snip2.tcllappend inputList /work/users/chcheng/BAS/moose-dstarpiset NEvent 100set histFileName momentum-2.rootmod talk MomentumSpectrum btaMicroList set GoodTracksLooseexitsourceFoundFile BetaMiniUser/MomentumSpectrum.tcl

Change the input list

What BtaCandidate lists are available to me?

A more complicated exampleMake combinations: e.g., D0→K−π+

Create an ntuple.

• get example code

• modify AppUserBuildBase.cc

• clean, compile and link‣ after adding new code, it is always a good idea to

do |gmake clean| and build from scratch, to avoid unforeseen complications.

• The header file (MyD0toKpi.hh) is almost identical to the previous example, except that it has an ntuple, instead of histograms, and a new module tcl parameter for the output list name (and of course the name).

27

Again copy a few files from my directory to your BetaMiniUser directory% cd ..% cp ~chcheng/babar/BAS/bas-a51-1/BetaMiniUser/MyD0toKpi* BetaMiniUser/

#include "BetaMiniUser/MyD0toKpi.hh"...... theBuild->add( new MyD0toKpi("MyD0toKpi", "My D0 -> K- pi+"));

% bsub -q bldrecoq -o log gmake clean lib BetaMiniUser.bin

protected: ... AbsParmIfdStrKey _outputList; ... HepTuple *_ntuple; ...

The code

28

// MyD0toKpi.cc //...AppResultMyD0toKpi::beginJob( AbsEvent* anEvent ){ HepTupleManager* _manager = gblEnv->getGen()->ntupleManager(); assert(_manager != 0); // book an ntuple _ntuple= _manager->ntuple("My D0 -> K pi"); return AppResult::OK;}

AppResultMyD0toKpi::event( AbsEvent* anEvent ){ _ievt++; //... // particle types we need static const PdtEntry* pdtKp= Pdt::lookup("K+"); static const PdtEntry* pdtKm= Pdt::lookup("K-"); static const PdtEntry* pdtPip= Pdt::lookup("pi+"); static const PdtEntry* pdtPim= Pdt::lookup("pi-"); static const PdtEntry* pdtD0= Pdt::lookup("D0"); static const PdtEntry* pdtD0b= Pdt::lookup("anti-D0");

// A few variables to store for ntuple HTValOrderedVector<double> d0mass, d0p3, d0costheta; HTValOrderedVector<int> d0pdgid; HTValOrderedVector<bool> d0true;

// Create a new list and put it into the event through its proxy. // This list will be available for subsequent modules. HepAList<BtaCandidate>* myD0list= new HepAList<BtaCandidate>; IfdHepAListProxy<BtaCandidate>* p = new IfdHepAListProxy<BtaCandidate>( myD0list );

if (!Ifd<HepAList< BtaCandidate > >::put(anEvent, p, _outputList.value())) { ErrMsg(fatal) << "Failed to put " << _outputList.value() << " into event." << endmsg; }

// Make two iterator from the same list HepAListIterator<BtaCandidate> iter1(*trkList); HepAListIterator<BtaCandidate> iter2(*trkList); // Nest two loops unsigned nCand=0; while ( BtaCandidate *c1= iter1() ) { // clone it and assign it a particle type BtaCandidate *k1= new BtaCandidate(*c1); if ( k1->charge() > 0 ) k1->setType(pdtKp); else k1->setType(pdtKm); while ( BtaCandidate *c2= iter2() ) { if ( c2->charge() == c1->charge() ) continue; BtaCandidate *p1= new BtaCandidate(*c2); if ( p1->charge() > 0 ) p1->setType(pdtPip); else p1->setType(pdtPim); // Combine the two tracks to become a D0 BtaOpMakeTree comb; BtaCandidate *myD = comb.create(*k1, *p1); if ( k1->charge() > 0 ) myD->setType(pdtD0b); else myD->setType(pdtD0); // Make cuts if ( myD->mass() > 2.2 ) continue; if ( myD->mass() < 1.4 ) continue; // Add this D candidate to the newly created list. myD0list->append(myD); } } // Loop over the D0 list and fill some variable to the ntuple HepAListIterator<BtaCandidate> itD0(*myD0list); while ( BtaCandidate *cand= itD0() ) { bool istrued0= false; // Get the truth partner if available if (truthMap) { const BtaCandidate *mc= truthMap->mcFromReco(cand,0,true); if ( mc ) istrued0= true; } // append the values to the ntuple's vector variables d0pdgid.append(cand->pdtEntry()->pdgId()); d0mass.append(cand->mass()); d0p3.append(cand->p()); d0costheta.append(cand->p4().cosTheta()); d0true.append(istrued0); }

The code (cont.) and tcl

• The tcl snippet

29

// MyD0toKpi.cc continues here // Dump this event to the ntuple _ntuple->column("ievt",(int)_ievt); _ntuple->column("nD0", (int)nCand); _ntuple->column("D0Mass",d0mass,"nD0",0,"D0"); _ntuple->column("D0pdg",d0pdgid,"nD0",0,"D0"); _ntuple->column("D0p3",d0p3,"nD0",0,"D0"); _ntuple->column("D0costheta",d0costheta,"nD0",0,"D0"); _ntuple->column("D0true",d0true,"nD0",0,"D0");

_ntuple->dumpData(); return AppResult::OK;}

## The input file is a collection from SP production, SP-1140lappend inputList /store/SP/R24/001140/run5/24.3.5/SP_001140_098221## 1000 events this timeset NEvent 1000set histFileName myd0tokpi.rootsourceFoundFile BetaMiniUser/MyD0toKpi.tcl

## What is SP-1140 ??% BbkSPModes -n 1140: Mode : Decfile : Generator : Filter : Run Type :: 1140 : ccbar_Dstar-_D0pi_D0Kpi.dec : continuum : D*- : ccbar->D*-->D0barpi-, D0bar->K+pi- :

• The main tcl (MyD0toKpi.tcl) is pretty much the same as MomentumSpectrum.tcl, except we append a different user module to the path and make the log file less verbose.

• Run the job

## Add Analysis module##path append Everything MyD0toKpi

## less verbosetalkto EvtCounter { printFreq set 100}

% cd workdir% BetaMiniApp ../BetaMiniUser/MyD0toKpi.snip.tcl |& tee myd0tokpi.log

OR use a batch queue% bsub -q kanga -o myd0tokpi.log BetaMiniApp ../BetaMiniUser/MyD0toKpi.snip.tcl

• A new ntuple named ntp1

What’s in the root file?

30

% bbrroot -l myd0tokpi.root...root [0] Attaching file myd0tokpi.root as _file0...root [1] .lsTFile** myd0tokpi.root Created for you by RooTupleManager TFile* myd0tokpi.root Created for you by RooTupleManager KEY: TH1F h1d1;1 Cherenkov angle... KEY: TH1F h1d20;1 Reco track momentum KEY: TH1F h1d21;1 Reco-mc track momentum diff. KEY: TTree ntp1;1 My D0 -> K pi

root [2] ntp1->Print()*******************************************************************************Tree :ntp1 : My D0 -> K pi **Entries : 1000 : Total = 60140 bytes File Size = 33898 ** : : Tree compression factor = 1.69 ********************************************************************************Br 0 :ievt : ievt/I **Entries : 1000 : Total Size= 4620 bytes One basket in memory **Baskets : 0 : Basket Size= 8000 bytes Compression= 1.00 **............................................................................**Br 1 :nD0 : nD0/I **Entries : 1000 : Total Size= 4614 bytes One basket in memory **Baskets : 0 : Basket Size= 8000 bytes Compression= 1.00 **............................................................................**Br 2 :D0Mass : D0Mass[nD0]/D **Entries : 1000 : Total Size= 12236 bytes File Size = 4509 **Baskets : 1 : Basket Size= 8000 bytes Compression= 1.32 **............................................................................**Br 3 :D0pdg : D0pdg[nD0]/I **Entries : 1000 : Total Size= 8502 bytes File Size = 1284 **Baskets : 1 : Basket Size= 8000 bytes Compression= 4.14 **............................................................................**Br 4 :D0p3 : D0p3[nD0]/D **Entries : 1000 : Total Size= 12222 bytes File Size = 4598 **Baskets : 1 : Basket Size= 8000 bytes Compression= 1.30 **............................................................................**Br 5 :D0costheta : D0costheta[nD0]/D **Entries : 1000 : Total Size= 12264 bytes File Size = 4568 **Baskets : 1 : Basket Size= 8000 bytes Compression= 1.30 **............................................................................**Br 6 :D0true : D0true[nD0]/b **Entries : 1000 : Total Size= 5726 bytes File Size = 1400 **Baskets : 1 : Basket Size= 8000 bytes Compression= 3.19 **............................................................................*

One entry per event

Vectors, nD0 values per event.We often call this a block in this ntuple.

Plots

31

root [3] ntp1->Draw("nD0")

root [4] ntp1->Draw("D0Mass")root [5] ntp1->SetFillStyle(1001)root [6] ntp1->SetFillColor(kBlue)root [7] ntp1->Draw("D0Mass","D0true","same")(Long64_t)88

root [12] ntp1->SetMarkerStyle(20) root [13] ntp1->Draw("D0p3:D0costheta")

Useful analysis tools that help you start with ease

32

Analysis tools• We now know how to ‣ get BtaCandidate lists from an event‣ loop over the entries in the list and extract

information‣ combine candidates to form composites‣ create and fill histograms and ntuples

• We did not talk about‣ applying constrains to candidates‣ fitting and vertexing‣ other more complicated manipulations

33

• Do I have to write all the code? For sure my analysis will be much more complicated than the examples.

• These seem to be common operations. For sure someone has written nice tools for us to use.

• Yes. You can find them from this Physics Software webpage.

For the remaining of today’s session, we will concentrate on two tools that allow you to build up your analysis and make ntuples without having to write a line of c++ code* and recompile every time you change your analysis,SimpleComposition and BtaTupleMaker.

* In some cases, you still have to.** This statement does not include further analysis on the ntuple to extract physics, such as fitting for branching fraction, lifetime and CP violation.

BtaTupleMaker• BtaTupleMaker is a package that provides a

cloneable module for users to dump an nutple after their analysis modules/sequences.

• It provides an interface between the BtaCandidates and the ntuple.

• We have implemented as many as useful variables as possible, so you don’t have to write C++ code. (Of course many calculations are done in other packages written by many people. BtaTupleMaker simply uses them.)

• If the calculation is very specific to your analysis, you should write a dedicated module for it, rather than rely on BtaTupleMaker.

• The contents of the ntuple are highly configurable using tcl.

• The module parses the strings you pass to it through tcl that contain keys known to this module, to set up the ntuple structure and calculate or extract the quantities from the BtaCandidates. Each key represents a category of quantities.

34

B

D*π

D0π

Block

B

Dstar

D0

K

pi

• Basic operation: starting from a top-level BtaCandidate list (a persistent list in the event, or a temporary list created in the user analysis module), this ntuple maker navigates through the decay tree and fill ntuple columns in different blocks according the particle types.

• It will append new candidates to the list, or find the index of the existing candidate, unless you instruct it to append anyway, without checking if clones exist.

Add BTM to our previous example• Add the module to our application:

• Let the compiler know that BetaMiniUser depends on BtaTupleMaker package:

• Copy two tcl files:

• Recompile:

• Again, tcl snippet is simple:

• This time, no C++ code to look at. ☺

35

// Add two lines to BetaMiniUser/AppUserBuildBase.cc#include "BtaTupleMaker/BtuTupleMaker.hh"... theBuild->add( new BtuTupleMaker("BtuTupleMaker", "Ntuple maker"));

## Add one line to BetaMiniUser/link_BetaMiniUser.mk...override LINK_BtaTupleMaker += BetaMiniUser

% cp ~chcheng/babar/BAS/bas-a51-1/BetaMiniUser/tuplemaker-MyD0toKpi* BetaMiniUser/

# tuplemaker-MyD0toKpi.snip.tcl lappend inputList /store/SP/R24/001140/run5/24.3.5/SP_001140_098221set NEvent 1000set histFileName tm-myd0tokpi.rootsourceFoundFile BetaMiniUser/tuplemaker-MyD0toKpi.tcl

% bsub -q bldrecoq -o log gmake clean lib BetaMiniUser.bin

The tcl configuration

36

## tuplemaker-MyD0toKpi.tcl## ...

## create Everything path and add core sequences to it.###sourceFoundFile BetaMiniUser/btaMini.tclsourceFoundFile BetaMiniUser/btaMiniPhysics.tcl#sourceFoundFile BetaMiniUser/btaMiniPhysProdSequence.tcl

## Add Analysis module##path append Everything MyD0toKpipath append Everything BtuTupleMaker

Use this to pull in more physics

sequences/modules

## Configure BtaTupleMakertalkto BtuTupleMaker { listToDump set MyD0ToKpi fillMC set true

eventBlockContents set "EventID CMp4 BeamSpot" eventTagsInt set "nTracks nGoodTrkLoose" eventTagsFloat set "R2All"

mcBlockContents set "Mass CMMomentum Momentum Vertex"

ntpBlockConfigs set "D0 D0 2 30" ntpBlockConfigs set "K+ K 0 20" ntpBlockConfigs set "pi+ Pi 0 20"

ntpBlockToTrk set "K Pi"

ntpBlockContents set "D0 : Mass CMMomentum Vertex MCIdx" ntpBlockContents set "K : Momentum" ntpBlockContents set "Pi : Momentum" ntpBlockContents set "TRK : MCIdx"

trkExtraContents set HOTS trkExtraContents set BitMap:KSelectorsMap,TracksMap}

The D0 list created by MyD0toKpi module

Event-level quantities

Quantites associated with MC truth BtaCandidates

Configure the block of each particle type in the decay chain: “[particle (pdt) name] [block name] [max # of daughters]

[max # of entries stored]”

Names of blocks that you want to link to TRK block

Configure each block. Sepcify which quantites you want to store for this particle block.

“[block name] : [key1] [key2]..”

Additional information for TRK block. “[key]:[option],[option],...”

Ntuple content• Run the job

• A new ntuple named ntp2

37

% cd workdir% BetaMiniApp ../BetaMiniUser/tuplemaker-MyD0toKpi.snip.tcl

% bbrroot -l tm-myd0tokpi.root...root [0] Attaching file tm-myd0tokpi.root as _file0...root [1] .ls... KEY: TH1F h1d1;1 Cherenkov angle... KEY: TTree ntp1;1 My D0 -> K pi KEY: TTree ntp2;1 myNtuple

root [2] ntp2->Print()***************************************Tree :ntp2 : myNtuple *Entries : 660 : Total = * : : Tree compression***************************************Br 0 :runNumber : runNumber/I *Entries : 660 : Total Size= *Baskets : 0 : Basket Size= *.....................................*Br 1 :platform : platform/I *Entries : 660 : Total Size= *Baskets : 0 : Basket Size= *.....................................*Br 2 :partition : partition/I *Entries : 660 : Total Size= *Baskets : 0 : Basket Size= *.....................................*Br 3 :upperID : upperID/I *Entries : 660 : Total Size= *Baskets : 0 : Basket Size=

*Br 23 :mcLen : mcLen/I *Entries : 660 : Total Size= 3*Baskets : 0 : Basket Size= 8*.........................................*Br 24 :mcLund : mcLund[mcLen]/I *Entries : 660 : Total Size= 111*Baskets : 14 : Basket Size= 8*.........................................*Br 25 :mothIdx : mothIdx[mcLen]/I *Entries : 660 : Total Size= 111*Baskets : 14 : Basket Size= 8*.........................................*Br 26 :dauLen : dauLen[mcLen]/I *Entries : 660 : Total Size= 111*Baskets : 14 : Basket Size= 8

*Br 40 :nD0 : nD0/I *Entries : 660 : Total Size= 3*Baskets : 0 : Basket Size= 8*.........................................*Br 41 :D0Mass : D0Mass[nD0]/F *Entries : 660 : Total Size= 7*Baskets : 1 : Basket Size= 8*.........................................*Br 42 :D0MassErr : D0MassErr[nD0]/F *Entries : 660 : Total Size= 7*Baskets : 1 : Basket Size= 8*.........................................*Br 43 :D0Vtxx : D0Vtxx[nD0]/F *Entries : 660 : Total Size= 7*Baskets : 1 : Basket Size= 8

Even

t-lev

el q

uant

ities

MC

trut

h lis

tD

0 bl

ock

Ntuple content

38

*Br 56 :nK : nK/I *Entries : 660 : Total Size= 3*Baskets : 0 : Basket Size= 8*.........................................*Br 57 :Kcosth : Kcosth[nK]/F *Entries : 660 : Total Size= 5*Baskets : 0 : Basket Size= 8*.........................................*Br 58 :Kenergy : Kenergy[nK]/F *Entries : 660 : Total Size= 6*Baskets : 0 : Basket Size= 8*.........................................*Br 59 :Kp3 : Kp3[nK]/F *Entries : 660 : Total Size= 5*Baskets : 0 : Basket Size= 8

*Br 63 :nPi : nPi/I *Entries : 660 : Total Size= 3*Baskets : 0 : Basket Size= 8*.........................................*Br 64 :Picosth : Picosth[nPi]/F *Entries : 660 : Total Size= 7*Baskets : 1 : Basket Size= 8*.........................................*Br 65 :Pienergy : Pienergy[nPi]/F *Entries : 660 : Total Size= 7*Baskets : 1 : Basket Size= 8*.........................................*Br 66 :Pip3 : Pip3[nPi]/F *Entries : 660 : Total Size= 7*Baskets : 1 : Basket Size= 8

*Br 70 :nTRK : nTRK/I *Entries : 660 : Total Size= 3*Baskets : 0 : Basket Size= 8*.........................................*Br 71 :TRKLund : TRKLund[nTRK]/I *Entries : 660 : Total Size= 9*Baskets : 1 : Basket Size= 8*.........................................*Br 72 :TRKMCIdx : TRKMCIdx[nTRK]/I *Entries : 660 : Total Size= 9*Baskets : 1 : Basket Size= 8*.........................................*Br 73 :TRKnSvt : TRKnSvt[nTRK]/I *Entries : 660 : Total Size= 9*Baskets : 1 : Basket Size= 8*.........................................*Br 74 :TRKnDch : TRKnDch[nTRK]/I *Entries : 660 : Total Size= 9*Baskets : 1 : Basket Size= 8*.........................................*Br 75 :TRKnHit : TRKnHit[nTRK]/I *Entries : 660 : Total Size= 9*Baskets : 1 : Basket Size= 8*.........................................*Br 76 :KSelectorsMap : KSelectorsMap[nT*Entries : 660 : Total Size= 9*Baskets : 1 : Basket Size= 8*.........................................*Br 77 :TracksMap : TracksMap[nTRK]/I *Entries : 660 : Total Size= 9*Baskets : 1 : Basket Size= 8

TRK

blo

ck

Pi b

lock

K b

lock

Analyze this ntuple

• More detail can be found in the README file and this webpage.

39

root [1] ntp2->Draw("D0Mass")<TCanvas::MakeDefCanvas>: created default TCanvas with name c1root [2] ntp2->SetLineColor(kRed)root [3] ntp2->SetFillStyle(3005)root [4] ntp2->SetFillColor(kRed)root [5] ntp2-> Draw("D0Mass","KSelectorsMap[KTrkIdx[D0d1Idx]]>0",”same”)

variable to draw

bit map of kaon idof a track

index of the vector that stores trackscorresponding to this kaon candidate

index of D0’s first daughter

This is how you make a cut interactively and how you connect different blocks through indexes.

SimpleComposition• SimpleComposition (SMP) is a BaBar package for creating lists of composite particles. The

output is stored in the event as an object of type HepAList<BtaCandidate>. Lists are specified by a decay mode and a set of daughter lists, which are themselves of type   HepAList<BtaCandidate>. Candidates on the output list are created by combining candidates from the daughter lists, subject to selections that can also be specified in the list definition.

• In SMP lists are completely defined by tcl by cloning from a base module. Therefore, it is not necessary to create and link new modules into your application for every new list.

• Besides modules to create new lists, SimpleComposition also provides modules to alter existing lists, for example to make a subselection or to add kinematic constraints.

• SimpleComposition User Guide is a very nicely written documentation. We will go through it in detail and then we will go through the final exercise today.

• Let’s take a look what are in SimpleComposition package. And one of the production Smp sequences, SmpEtaProdSequence.tcl.

40

One more example using Smp• Check out BtaTupleMaker package. You can

also build an executable with it. It includes a few more physics sequences/modules than BetaMiniUser

• This time we are building B0→J/ψ KS0 with J/ψ→ e+e− or µ+µ−, and KS0→π+π−.

• From this link, you can find this signal MC mode number 1026. Or use BbkSPModes utility.

• Find the datasets using BbkDatasetTcl.

• Set up the tcl snippet

41

% addpkg BtaTupleMaker% bsub -q bldrecoq -o log3 gmake BtaTupleMaker.bin...% which BtaTupleApp./bin/Linux26SL4_i386_gcc346/BtaTupleApp

% BbkSPModes -h ## for help% BbkSPModes -n 1026: Mode : Decfile : Generator : Filter : Run Type :: 1026 : B0B0bar_JpsiKS_+-.dec : Upsilon(4S) : : B0 -> X, B0~ -> J/psi(e+e-/mu+mu-)K0s(pi+pi-) + c.c. :

% BbkDatasetTcl -h ## for help% BbkDatasetTcl --dbname bbkr24 -l SP-1026\*BbkDatasetTcl: 18 datasets found in bbkr24 at slac:-

SP-1026-60ifbR24-v01SP-1026-AllEventsSkim-R24a1...SP-1026-Run5-R24...% BbkDatasetTcl --dbname bbkr24 -ds SP-1026-Run5-R24BbkDatasetTcl: wrote SP-1026-Run5-R24.tclSelected 31 collections, 3997000/3997000 events, from bbkr24 at slac

## workdir/smp-example.snip.tcllappend inputList /store/SP/R24/001026/run5/24.3.5/SP_001026_075559set NEvent 8000set histFileName smp-example.rootsourceFoundFile smp-example.tcl

a collection in SP-1026-Run5-R24.tcl.You can also source this tcl.

The tcl file

42

## workdir/smp-example.tcl## The beginning is the same as previous examples## ...

## create Everything path and add core sequences to it.###sourceFoundFile BetaMiniUser/btaMini.tclsourceFoundFile BetaMiniUser/btaMiniPhysics.tcl#sourceFoundFile BetaMiniUser/btaMiniPhysProdSequence.tcl

## less verbosetalkto EvtCounter { printFreq set 100}################################################# User analysis Smp sequence start hereseq create MySmpSequence

## set some variablesset muonTrack GoodTracksLooseset muonLoose muNNVeryLooseset elecTrack GoodTracksLooseset elecLoose eMicroVeryLoose

## Make J/psi ## J/psi -> mu+ mu- mod clone SmpMakerDefiner JPsiToMuMuLooseseq append MySmpSequence JPsiToMuMuLoosetalkto JPsiToMuMuLoose { decayMode set "J/psi -> mu+ mu-" daughterListNames set $muonLoose daughterListNames set $muonTrack fittingAlgorithm set "Cascade" fitConstraints set "Geo" preFitSelectors set "Mass 2.5:3.5" postFitSelectors set "Mass 2.8:3.3"}

## J/psi -> e+ e- mod clone SmpMakerDefiner JPsiToEELooseseq append MySmpSequence JPsiToEELoosetalkto JPsiToEELoose { decayMode set "J/psi -> e+ e-" daughterListNames set $elecLoose daughterListNames set $elecTrack fittingAlgorithm set "Cascade" fitConstraints set "Geo" preFitSelectors set "Mass 2.3:3.5" postFitSelectors set "Mass 2.5:3.3"}# Merge EE and MuMu mod clone SmpMergerDefiner JPsiLooseseq append MySmpSequence JPsiLoosetalkto JPsiLoose { inputListNames set JPsiToEELoose inputListNames set JPsiToMuMuLoose disableCloneCheck set t debug set $JPsiDebug verbose set $JPsiVerbose}## B0 -> J/psi KS mod clone SmpMakerDefiner BToJpsiKsseq append MySmpSequence BToJpsiKstalkto BToJpsiKs { decayMode set "B0 -> J/psi K_S0" daughterListNames set JPsiLoose daughterListNames set KsLoose fittingAlgorithm set "Cascade" fitConstraints set "Geo" preFitSelectors set "DeltaE -0.1:0.1" preFitSelectors set "Mes 5.17:5.30" postFitSelectors set "DeltaE -0.05:0.05" postFitSelectors set "Mes 5.20:5.30" disableCloneCheck set t createUsrData set t}

The tcl file (cont.)

43

## Refit with mass constraint on J/psi mod clone SmpRefitterDefiner BToJpsiKsTightseq append MySmpSequence BToJpsiKsTighttalkto BToJpsiKsTight { unrefinedListName set BToJpsiKs postFitSelectors set "DeltaE" postFitSelectors set "Mes" fittingAlgorithm set "TreeFitter" fitConstraints set "Mass J/psi" createUsrData set t}

## Add the sequence to the path path append Everything MySmpSequence## ## Tagging sourceFoundFile BTaggingSequences/BtsTaggingSequence.tclpath append Everything BtsTaggingSequence

talkto BtsTaggingDispatch { production set t BRecList set BToJpsiKsTight tagCandList set TagSideCandidates Y4SList set Y4SList tagger set BtgBTaggerTag08 show}

## Dump ntuple talkto BtuTupleMaker { ntupleName set BToJpsiKs listToDump set BToJpsiKsTight

eventBlockContents set "EventID CMp4 BeamSpot" mcBlockContents set "Mass CMMomentum Momentum Vertex"

ntpBlockConfigs set "B0 B 2 50" ntpBlockConfigs set "J/psi Jpsi 2 50" ntpBlockConfigs set "K_S0 KS 2 50" ntpBlockConfigs set "pi+ pi 0 100" ntpBlockConfigs set "e+ e 0 30" ntpBlockConfigs set "mu+ mu 0 30" ntpBlockContents set "B : MCIdx CMMomentum Vertex VtxCov VtxChi2 TagVtx UsrData(BToJpsiKsTight)" ntpBlockContents set "Jpsi : Mass MCIdx Vertex VtxChi2" ntpBlockContents set "KS : Mass Vertex VtxChi2 MCIdx" ntpBlockContents set "pi : Momentum MCIdx" ntpBlockContents set "e : Momentum MCIdx" ntpBlockContents set "mu : Momentum MCIdx"

checkClones set false checkCloneBlocks set "KS pi e mu"

ntpBlockToTrk set "e mu pi" fillAllCandsInList set "TRK ChargedTracks"

ntpBlockContents set "TRK : Momentum MCIdx"

writeEveryEvent set false fillMC set true}

## Add tuple maker module path append Everything BtuTupleMaker

### ...### ...

Make plots with a simple macro

44

tagging < -0.2

Other useful information• Debug: See this HOWTO/HOWTO-Basic-Debugging for detail. If you are using linux (like

most people), gdb is most useful.• Hypernews: the way Babarians communicate. You should subscribe those that interest you. Most

important forums (and I strongly suggest you subscribe to) are ‣ Physics Analysis --- broader physics issues‣ Preliminary/unconfirmed Bugs, Problems, Frustrations, Fixes --- technical problems you are not sure

which system is at fault.‣ SLAC Computing Outages and Changes --- important announcement (only experts are allowed to post)‣ Programming questions

• Search before you ask. The hypernews search engine is not the greatest one, but very often if you plug in the error messages, you will find the issue has been discussed before and usually you can find the solution without asking. You can also learn who are likely to be the expert of certain area.

45

It’s just the beginning•I hope you enjoy today’s tutorial and have learned something to let you

start working on BABAR data without feeling overwhelmed by the complexity of BABAR offline computing.

•Feel free to ask me or other experienced Babarians questions.

46

THE END (for today)