6.2.1. ModularAnalysis¶

This module defines wrapper functions around the analysis modules.

Adds the InclusiveDstarReconstruction module to the given path. This module creates a D* particle list by estimating the D* four momenta from slow pions, specified by a given cut. The D* energy is approximated as E(D*) = m(D*)/(m(D*) - m(D)) * E(pi). The absolute value of the D* momentum is calculated using the D* PDG mass and the direction is collinear to the slow pion direction. The charge of the given pion list has to be consistent with the D* charge

Parameters
• decayString – Decay string, must be of form D* -> pi

• slowPionCut – Cut applied to the input pion list to identify slow pions

• DstarCut – Cut applied to the output D* list

• path – the module is added to this path

Add photon Data/MC detection efficiency ratio weights to the specified particle list

Parameters
• inputListNames (list(str)) – input particle list names

• tableName – taken from database with appropriate name

• path (basf2.Path) – module is added to this path

Loads the ROE object of a particle and creates a ROE mask with a specific name. It applies selection criteria for tracks and eclClusters which will be used by variables in ROEVariables.cc.

• append a ROE mask with all tracks in ROE coming from the IP region

appendROEMask('B+:sig', 'IPtracks', '[dr < 2] and [abs(dz) < 5]', path=mypath)

• append a ROE mask with only ECL-based particles that pass as good photon candidates

goodPhotons = 'inCDCAcceptance and clusterErrorTiming < 1e6 and [clusterE1E9 > 0.4 or E > 0.075]'

Parameters
• list_name – name of the input ParticleList

• trackSelection – decay string for the track-based particles in ROE

• eclClusterSelection – decay string for the ECL-based particles in ROE

• klmClusterSelection – decay string for the KLM-based particles in ROE

• path – modules are added to this path

Loads the ROE object of a particle and creates a ROE mask with a specific name. It applies selection criteria for track-, ECL- and KLM-based particles which will be used by ROE variables.

The multiple ROE masks with their own selection criteria are specified via list of tuples (mask_name, trackParticleSelection, eclParticleSelection, klmParticleSelection) or (mask_name, trackSelection, eclClusterSelection) in case with fractions.

• Example for two tuples, one with and one without fractions

ipTracks     = ('IPtracks', '[dr < 2] and [abs(dz) < 5]', '', '')
goodPhotons = 'inCDCAcceptance and [clusterErrorTiming < 1e6] and [clusterE1E9 > 0.4 or E > 0.075]'
goodROEGamma = ('ROESel', '[dr < 2] and [abs(dz) < 5]', goodPhotons, '')
goodROEKLM     = ('IPtracks', '[dr < 2] and [abs(dz) < 5]', '', 'nKLMClusterTrackMatches == 0')

Parameters
• list_name – name of the input ParticleList

• path – modules are added to this path

modularAnalysis.applyChargedPidMVA(particleLists, path, trainingMode, chargeIndependent=False, binaryHypoPDGCodes=(0, 0))[source]

Use an MVA to perform particle identification for charged stable particles, using the ChargedPidMVA module.

The module decorates Particle objects in the input ParticleList(s) with variables containing the appropriate MVA score, which can be used to select candidates by placing a cut on it.

Note

The MVA algorithm used is a gradient boosted decision tree (TMVA 4.3.0, ROOT 6.20/04).

The module can perform either ‘binary’ PID between input S, B particle mass hypotheses according to the following scheme:

• e (11) vs. pi (211)

• mu (13) vs. pi (211)

• pi (211) vs. K (321)

• K (321) vs. pi (211)

, or ‘global’ PID, namely “one-vs-others” separation. The latter exploits an MVA algorithm trained in multi-class mode, and it’s the default behaviour. Currently, the multi-class training separates the following standard charged hypotheses:

• e (11), mu (13), pi (211), K (321)

Warning

In order to run the ChargedPidMVA and ensure the most up-to-date MVA training weights are applied, it is necessary to append the latest analysis global tag (GT) to the steering script.

Parameters
• particleLists (list(str)) – list of names of ParticleList objects for charged stable particles. The charge-conjugate ParticleLists will be also processed automatically.

• path (basf2.Path) – the module is added to this path.

• trainingMode (Belle2.ChargedPidMVAWeights.ChargedPidMVATrainingMode) –

enum identifier of the training mode. Needed to pick up the correct payload from the DB. Available choices:

• c_Classification=0

• c_Multiclass=1

• c_ECL_Classification=2

• c_ECL_Multiclass=3

• c_PSD_Classification=4

• c_PSD_Multiclass=5

• c_ECL_PSD_Classification=6

• c_ECL_PSD_Multiclass=7

• chargeIndependent (bool, optional) – use a BDT trained on a sample of inclusively charged particles.

• binaryHypoPDGCodes (tuple(int, int), optional) – the pdgIds of the signal, background mass hypothesis. Required only for binary PID mode.

modularAnalysis.applyCuts(list_name, cut, path)[source]

Removes particle candidates from list_name that do not pass cut (given selection criteria).

Example

require energetic pions safely inside the cdc

applyCuts("pi+:mypions", "[E > 2] and thetaInCDCAcceptance", path=mypath)


Warning

You must use square braces [ and ] for conditional statements.

Parameters
• list_name (str) – input ParticleList name

• cut (str) – Candidates that do not pass these selection criteria are removed from the ParticleList

• path (basf2.Path) – modules are added to this path

modularAnalysis.applyEventCuts(cut, path)[source]

Removes events that do not pass the cut (given selection criteria).

Example

continuum events (in mc only) with more than 5 tracks

applyEventCuts("[nTracks > 5] and [isContinuumEvent], path=mypath)


Warning

You must use square braces [ and ] for conditional statements.

Parameters
• cut (str) – Events that do not pass these selection criteria are skipped

• path (basf2.Path) – modules are added to this path

modularAnalysis.applyRandomCandidateSelection(particleList, path=None)[source]

If there are multiple candidates in the provided particleList, all but one of them are removed randomly. This is done on a event-by-event basis.

Parameters
• particleList – ParticleList for which the random candidate selection should be applied

• path – module is added to this path

Creates for each Particle in the given ParticleList a ContinuumSuppression dataobject and makes basf2 relation between them.

Parameters
• list_name – name of the input ParticleList

• path – modules are added to this path

modularAnalysis.buildEventKinematics(inputListNames=None, default_cleanup=True, custom_cuts=None, chargedPIDPriors=None, fillWithMostLikely=False, path=None)[source]

Calculates the global kinematics of the event (visible energy, missing momentum, missing mass…) using ParticleLists provided. If no ParticleList is provided, default ParticleLists are used (all track and all hits in ECL without associated track).

The visible energy missing values are stored in a EventKinematics dataobject.

Parameters
• inputListNames – list of ParticleLists used to calculate the global event kinematics. If the list is empty, default ParticleLists pi+:evtkin and gamma:evtkin are filled.

• fillWithMostLikely – if True, the module uses the most likely particle mass hypothesis for charged particles according to the PID likelihood and the option inputListNames will be ignored.

• chargedPIDPriors – The prior PID fractions, that are used to regulate amount of certain charged particle species, should be a list of six floats if not None. The order of particle types is the following: [e-, mu-, pi-, K-, p+, d+]

• default_cleanup – if True and either inputListNames empty or fillWithMostLikely True, default clean up cuts are applied

• custom_cuts – tuple of selection cut strings of form (trackCuts, photonCuts), default is None, which would result in a standard predefined selection cuts

• path – modules are added to this path

modularAnalysis.buildEventKinematicsFromMC(inputListNames=None, selectionCut='', path=None)[source]

Calculates the global kinematics of the event (visible energy, missing momentum, missing mass…) using generated particles. If no ParticleList is provided, default generated ParticleLists are used.

Parameters
• inputListNames – list of ParticleLists used to calculate the global event kinematics. If the list is empty, default ParticleLists are filled.

• selectionCut – optional selection cuts

• path – Path to append the eventKinematics module to.

modularAnalysis.buildEventShape(inputListNames=None, default_cleanup=True, custom_cuts=None, allMoments=False, cleoCones=True, collisionAxis=True, foxWolfram=True, harmonicMoments=True, jets=True, sphericity=True, thrust=True, checkForDuplicates=False, path=None)[source]

Calculates the event-level shape quantities (thrust, sphericity, Fox-Wolfram moments…) using the particles in the lists provided by the user. If no particle list is provided, the function will internally create a list of good tracks and a list of good photons with (optionally) minimal quality cuts.

The results of the calculation are then stored into the EventShapeContainer dataobject, and are accessible using the variables of the EventShape group.

The user can switch the calculation of certain quantities on or off to save computing time. By default the calculation of the high-order moments (5-8) is turned off. Switching off an option will make the corresponding variables not available.

Warning

The user can provide as many particle lists as needed, using also combined particles, but the function will always assume that the lists are independent. If the lists provided by the user contain several times the same track (either with different mass hypothesis, or once as an independent particle and once as daughter of a combined particle) the results won’t be reliable. A basic check for duplicates is available setting the checkForDuplicate flags, but is usually quite time consuming.

Parameters
• inputListNames – List of ParticleLists used to calculate the event shape variables. If the list is empty the default particleLists pi+:evtshape and gamma:evtshape are filled.

• default_cleanup – If True, applies standard cuts on pt and cosTheta when defining the internal lists. This option is ignored if the particleLists are provided by the user.

• custom_cuts – tuple of selection cut strings of form (trackCuts, photonCuts), default is None, which would result in a standard predefined selection cuts

• path – Path to append the eventShape modules to.

• thrust – Enables the calculation of thrust-related quantities (CLEO cones, Harmonic moments, jets).

• collisionAxis – Enables the calculation of the quantities related to the collision axis .

• foxWolfram – Enables the calculation of the Fox-Wolfram moments.

• harmonicMoments – Enables the calculation of the Harmonic moments with respect to both the thrust axis and, if collisionAxis = True, the collision axis.

• allMoments – If True, calculates also the FW and harmonic moments from order 5 to 8 instead of the low-order ones only.

• cleoCones – Enables the calculation of the CLEO cones with respect to both the thrust axis and, if collisionAxis = True, the collision axis.

• jets – Enables the calculation of the hemisphere momenta and masses. Requires thrust = True.

• sphericity – Enables the calculation of the sphericity-related quantities.

• checkForDuplicates – Perform a check for duplicate particles before adding them. This option is quite time consuming, instead of using it consider sanitizing the lists you are passing to the function.

Creates for each Particle in the given ParticleList a RestOfEvent

Parameters
• target_list_name – name of the input ParticleList

• path – modules are added to this path

modularAnalysis.buildRestOfEvent(target_list_name, inputParticlelists=None, fillWithMostLikely=True, chargedPIDPriors=None, path=None)[source]

Creates for each Particle in the given ParticleList a RestOfEvent dataobject and makes basf2 relation between them. User can provide additional particle lists with a different particle hypothesis like [‘K+:good, e+:good’], etc.

Parameters
• target_list_name – name of the input ParticleList

• inputParticlelists – list of user-defined input particle list names, which serve as source of particles to build the ROE, the FSP particles from target_list_name are automatically excluded from the ROE object

• fillWithMostLikely – By default the module uses the most likely particle mass hypothesis for charged particles based on the PID likelihood. Turn this behavior off if you want to configure your own input particle lists.

• chargedPIDPriors – The prior PID fractions, that are used to regulate the amount of certain charged particle species, should be a list of six floats if not None. The order of particle types is the following: [e-, mu-, pi-, K-, p+, d+]

• path – modules are added to this path

modularAnalysis.buildRestOfEventFromMC(target_list_name, inputParticlelists=None, path=None)[source]

Creates for each Particle in the given ParticleList a RestOfEvent

Parameters
• target_list_name – name of the input ParticleList

• inputParticlelists – list of input particle list names, which serve as a source of particles to build ROE, the FSP particles from target_list_name are excluded from ROE object

• path – modules are added to this path

modularAnalysis.calculateDistance(list_name, decay_string, mode='vertextrack', path=None)[source]

Calculates distance between two vertices, distance of closest approach between a vertex and a track, distance of closest approach between a vertex and btube. For track, this calculation ignores track curvature, it’s negligible for small distances.The user should use extraInfo(CalculatedDistance) to get it. A full example steering file is at analysis/tests/test_DistanceCalculator.py

Example

from modularAnalysis import calculateDistance
calculateDistance('list_name', 'decay_string', "mode", path=user_path)

Parameters
• list_name – name of the input ParticleList

• decay_string – select particles between the distance of closest approach will be calculated

• mode – Specifies how the distance is calculated vertextrack: calculate the distance of closest approach between a track and a vertex, taking the first candidate as vertex, default trackvertex: calculate the distance of closest approach between a track and a vertex, taking the first candidate as track 2tracks: calculates the distance of closest approach between two tracks 2vertices: calculates the distance between two vertices vertexbtube: calculates the distance of closest approach between a vertex and btube trackbtube: calculates the distance of closest approach between a track and btube

• path – modules are added to this path

modularAnalysis.calculateTrackIsolation(list_name, path, *detectors, use2DRhoPhiDist=False, alias=None)[source]

Given a list of charged stable particles, compute variables that quantify “isolation” of the associated tracks.

Currently, a proxy for isolation is defined as the 3D distance (or optionally, a 2D distance projecting on r-phi) of each particle’s track to its closest neighbour at a given detector entry surface.

Parameters
• list_name (str) – name of the input ParticleList. It must be a list of charged stable particles as defined in Const::chargedStableSet. The charge-conjugate ParticleList will be also processed automatically.

• path (basf2.Path) – the module is added to this path.

• use2DRhoPhiDist (Optional[bool]) – if true, will calculate the pair-wise track distance as the cord length on the (rho, phi) projection. By default, a 3D distance is calculated.

• alias (Optional[str]) – An alias to the extraInfo variable computed by the TrackIsoCalculator module. Please note, for each input detector a variable is calculated, and the detector’s name is appended to the alias to distinguish them.

• *detectors – detectors at whose entry surface track isolation variables will be calculated. Choose among: “CDC”, “PID”, “ECL”, “KLM” (NB: ‘PID’ indicates TOP+ARICH entry surface.)

modularAnalysis.combineAllParticles(inputParticleLists, outputList, cut='', writeOut=False, path=None)[source]

Creates a new Particle as the combination of all Particles from all provided inputParticleLists. However, each particle is used only once (even if duplicates are provided) and the combination has to pass the specified selection criteria to be saved in the newly created (mother) ParticleList.

Parameters
• inputParticleLists – List of input particle lists which are combined to the new Particle

• outputList – Name of the particle combination created with this module

• cut – created (mother) Particle is added to the mother ParticleList if it passes these given cuts (in VariableManager style) and is rejected otherwise

• writeOut – whether RootOutput module should save the created ParticleList

• path – module is added to this path

modularAnalysis.copyList(outputListName, inputListName, writeOut=False, path=None)[source]

Copy all Particle indices from input ParticleList to the output ParticleList. Note that the Particles themselves are not copied. The original and copied ParticleLists will point to the same Particles.

Parameters
• ouputListName – copied ParticleList

• inputListName – original ParticleList to be copied

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

modularAnalysis.copyLists(outputListName, inputListNames, writeOut=False, path=None)[source]

Copy all Particle indices from all input ParticleLists to the single output ParticleList. Note that the Particles themselves are not copied. The original and copied ParticleLists will point to the same Particles.

Duplicates are removed based on the first-come, first-served principle. Therefore, the order of the input ParticleLists matters.

If you want to select the best duplicate based on another criterion, have a look at the function mergeListsWithBestDuplicate.

Note

Two particles that differ only by the order of their daughters are considered duplicates and one of them will be removed.

Parameters
• ouputListName – copied ParticleList

• inputListName – vector of original ParticleLists to be copied

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

modularAnalysis.copyParticles(outputListName, inputListName, writeOut=False, path=None)[source]

Create copies of Particles given in the input ParticleList and add them to the output ParticleList.

The existing relations of the original Particle (or it’s (grand-)^n-daughters) are copied as well. Note that only the relation is copied and that the related object is not. Copied particles are therefore related to the same object as the original ones.

Parameters
• ouputListName – new ParticleList filled with copied Particles

• inputListName – input ParticleList with original Particles

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

modularAnalysis.correctBrems(outputList, inputList, gammaList, maximumAcceptance=3.0, multiplePhotons=False, usePhotonOnlyOnce=True, writeOut=False, path=None)[source]

For each particle in the given inputList, copies it to the outputList and adds the 4-vector of the photon(s) in the gammaList which has(have) a weighted named relation to the particle’s track, set by the ECLTrackBremFinder module during reconstruction.

Warning

This can only work if the mdst file contains the Bremsstrahlung named relation. Official MC samples up to and including MC12 and proc9 do not contain this. Newer production campaigns (from proc10 and MC13) do. However, studies by the tau WG revealed that the cuts applied by the ECLTrackBremFinder module are too tight. These will be loosened but this will only have effect with proc13 and MC15. If your analysis is very sensitive to the Bremsstrahlung corrections, it is advised to use correctBremsBelle.

Information:

A detailed description of how the weights are set can be found directly at the documentation of the BremsFinder module.

Please note that a new particle is always generated, with the old particle and -if found- one or more photons as daughters.

The inputList should contain particles with associated tracks. Otherwise, the module will exit with an error.

The gammaList should contain photons. Otherwise, the module will exit with an error.

Parameters
• outputList – The output particle list name containing the corrected particles

• inputList – The initial particle list name containing the particles to correct. It should already exist.

• gammaList – The photon list containing possibly bremsstrahlung photons; It should already exist.

• maximumAcceptance – Maximum value of the relation weight. Should be a number between [0,3)

• multiplePhotons – Whether to use only one photon (the one with the smallest acceptance) or as many as possible

• usePhotonOnlyOnce – If true, each brems candidate is used to correct only the track with the smallest relation weight

• writeOut – Whether RootOutput module should save the created outputList

• path – The module is added to this path

modularAnalysis.correctBremsBelle(outputListName, inputListName, gammaListName, multiplePhotons=True, angleThreshold=0.05, writeOut=False, path=None)[source]

Run the Belle - like brems finding on the inputListName of charged particles. Adds all photons in gammaListName to a copy of the charged particle that are within angleThreshold.

Tip

Studies by the tau WG show that using a rather wide opening angle (up to 0.2 rad) and rather low energetic photons results in good correction. However, this should only serve as a starting point for your own studies because the optimal criteria are likely mode-dependent

Parameters
• outputListName (str) – The output charged particle list containing the corrected charged particles

• inputListName (str) – The initial charged particle list containing the charged particles to correct.

• gammaListName (str) – The gammas list containing possibly radiative gammas, should already exist.

• multiplePhotons (bool) – How many photons should be added to the charged particle? nearest one -> False, add all the photons within the cone -> True

• angleThreshold (float) – The maximum angle in radians between the charged particle and the (radiative) gamma to be accepted.

• writeOut (bool) – whether RootOutput module should save the created ParticleList

• path (basf2.Path) – modules are added to this path

modularAnalysis.correctEnergyBias(inputListNames, tableName, path=None)[source]

Scale energy of the particles according to the scaling factor. If the particle list contains composite particles, the energy of the daughters are scaled. Subsequently, the energy of the mother particle is updated as well.

Parameters
• inputListNames (list(str)) – input particle list names

• tableName – stored in localdb and created using ParticleWeightingLookUpCreator

• path (basf2.Path) – module is added to this path

modularAnalysis.cutAndCopyList(outputListName, inputListName, cut, writeOut=False, path=None)[source]

Copy candidates from inputListName to outputListName if they pass cut (given selection criteria).

Note

Note the Particles themselves are not copied. The original and copied ParticleLists will point to the same Particles.

Example

require energetic pions safely inside the cdc

cutAndCopyList("pi+:energeticPions", "pi+:loose", "[E > 2] and thetaInCDCAcceptance", path=mypath)


Warning

You must use square braces [ and ] for conditional statements.

Parameters
• outputListName (str) – the new ParticleList name

• inputListName (str) – input ParticleList name

• cut (str) – Candidates that do not pass these selection criteria are removed from the ParticleList

• writeOut (bool) – whether RootOutput module should save the created ParticleList

• path (basf2.Path) – modules are added to this path

modularAnalysis.cutAndCopyLists(outputListName, inputListNames, cut, writeOut=False, path=None)[source]

Copy candidates from all lists in inputListNames to outputListName if they pass cut (given selection criteria).

Note

Note that the Particles themselves are not copied. The original and copied ParticleLists will point to the same Particles.

Example

Require energetic pions safely inside the cdc

cutAndCopyLists("pi+:energeticPions", ["pi+:good", "pi+:loose"], "[E > 2] and thetaInCDCAcceptance", path=mypath)


Warning

You must use square braces [ and ] for conditional statements.

Parameters
• outputListName (str) – the new ParticleList name

• inputListName (list(str)) – list of input ParticleList names

• cut (str) – Candidates that do not pass these selection criteria are removed from the ParticleList

• writeOut (bool) – whether RootOutput module should save the created ParticleList

• path (basf2.Path) – modules are added to this path

This function is used to apply particle list specific cuts on one or more ROE masks (track or eclCluster). With this function one can DISCARD the tracks/eclclusters used in particles from provided particle list. This function should be executed only in the for_each roe path for the current ROE object.

To avoid unnecessary computation, the input particle list should only contain particles from ROE (use cut ‘isInRestOfEvent == 1’). To update the ECLCluster masks, the input particle list should be a photon particle list (e.g. ‘gamma:someLabel’). To update the Track masks, the input particle list should be a charged pion particle list (e.g. ‘pi+:someLabel’).

Updating a non-existing mask will create a new one.

• discard tracks that were used in provided particle list

discardFromROEMasks('pi+:badTracks', 'mask', '', path=mypath)

• discard clusters that were used in provided particle list and pass a cut, apply to several masks

discardFromROEMasks('gamma:badClusters', ['mask1', 'mask2'], 'E < 0.1', path=mypath)

Parameters
• list_name – name of the input ParticleList

• cut_string – decay string with which the mask will be updated

• path – modules are added to this path

modularAnalysis.fillConvertedPhotonsList(decayString, cut, writeOut=False, path=None)[source]

Creates photon Particle object for each e+e- combination in the V0 StoreArray.

Note

You must specify the daughter ordering.

fillConvertedPhotonsList('gamma:converted -> e+ e-', '', path=mypath)

Parameters
• decayString (str) – Must be gamma to an e+e- pair. You must specify the daughter ordering. Will also determine the name of the particleList.

• cut (str) – Particles need to pass these selection criteria to be added to the ParticleList

• writeOut (bool) – whether RootOutput module should save the created ParticleList

• path (basf2.Path) – modules are added to this path

Creates Particles of the desired type from the corresponding mdst dataobjects, loads them to the StoreArray<Particle> and fills the ParticleList.

the Standard Particles functions.

The type of the particles to be loaded is specified via the decayString module parameter. The type of the mdst dataobject that is used as an input is determined from the type of the particle. The following types of the particles can be loaded:

• charged final state particles (input mdst type = Tracks)
• e+, mu+, pi+, K+, p, deuteron (and charge conjugated particles)

• neutral final state particles
• “gamma” (input mdst type = ECLCluster)

• “K_S0”, “Lambda0” (input mdst type = V0)

• “K_L0” (input mdst type = KLMCluster or ECLCluster)

Note

For “K_S0” and “Lambda0” you must specify the daughter ordering.

For example, to load V0s as $$\Lambda^0\to p^+\pi^-$$ decays from V0s:

fillParticleList('Lambda0 -> p+ pi-', '0.9 < M < 1.3', path=mypath)


Tip

Gammas can also be loaded from KLMClusters by explicitly setting the parameter loadPhotonsFromKLM to True. However, this should only be done in selected use-cases and the effect should be studied carefully.

Tip

For “K_L0” it is now possible to load from ECLClusters, to revert to the old (Belle) behavior, you can require 'isFromKLM > 0'.

fillParticleList('K_L0', 'isFromKLM > 0', path=mypath)

Parameters
• decayString (str) – Type of Particle and determines the name of the ParticleList. If the input MDST type is V0 the whole decay chain needs to be specified, so that the user decides and controls the daughters’ order (e.g. K_S0 -> pi+ pi-)

• cut (str) – Particles need to pass these selection criteria to be added to the ParticleList

• writeOut (bool) – whether RootOutput module should save the created ParticleList

• path (basf2.Path) – modules are added to this path

• enforceFitHypothesis (bool) – If true, Particles will be created only for the tracks which have been fitted using a mass hypothesis of the exact type passed to fillParticleLists(). If enforceFitHypothesis is False (the default) the next closest fit hypothesis in terms of mass difference will be used if the fit using exact particle type is not available.

• loadPhotonsFromKLM (bool) – If true, photon candidates will be created from KLMClusters as well.

• loadPhotonBeamBackgroundMVA (bool) – If true, photon candidates will be assigned a beam background probability.

modularAnalysis.fillParticleListFromMC(decayString, cut, addDaughters=False, skipNonPrimaryDaughters=False, writeOut=False, path=None)[source]

Creates Particle object for each MCParticle of the desired type found in the StoreArray<MCParticle>, loads them to the StoreArray<Particle> and fills the ParticleList.

The type of the particles to be loaded is specified via the decayString module parameter.

Parameters
• decayString – specifies type of Particles and determines the name of the ParticleList

• cut – Particles need to pass these selection criteria to be added to the ParticleList

• addDaughters – adds the bottom part of the decay chain of the particle to the datastore and sets mother-daughter relations

• skipNonPrimaryDaughters – if true, skip non primary daughters, useful to study final state daughter particles

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

modularAnalysis.fillParticleListFromROE(decayString, cut, maskName='', sourceParticleListName='', useMissing=False, writeOut=False, path=None)[source]

Creates Particle object for each ROE of the desired type found in the StoreArray<RestOfEvent>, loads them to the StoreArray<Particle> and fills the ParticleList. If useMissing is True, then the missing momentum is used instead of ROE.

The type of the particles to be loaded is specified via the decayString module parameter.

Parameters
• decayString – specifies type of Particles and determines the name of the ParticleList. Source ROEs can be taken as a daughter list, for example: ‘B0:tagFromROE -> B0:signal’

• cut – Particles need to pass these selection criteria to be added to the ParticleList

• sourceParticleListName – Use related ROEs to this particle list as a source

• useMissing – Use missing momentum instead of ROE momentum

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

modularAnalysis.fillParticleListWithTrackHypothesis(decayString, cut, hypothesis, writeOut=False, enforceFitHypothesis=False, path=None)[source]

As fillParticleList, but if used for a charged FSP, loads the particle with the requested hypothesis if available

Parameters
• decayString – specifies type of Particles and determines the name of the ParticleList

• cut – Particles need to pass these selection criteria to be added to the ParticleList

• hypothesis – the PDG code of the desired track hypothesis

• writeOut – whether RootOutput module should save the created ParticleList

• enforceFitHypothesis – If true, Particles will be created only for the tracks which have been fitted using a mass hypothesis of the exact type passed to fillParticleLists(). If enforceFitHypothesis is False (the default) the next closest fit hypothesis in terms of mass difference will be used if the fit using exact particle type is not available.

• path – modules are added to this path

Creates Particles of the desired types from the corresponding mdst dataobjects, loads them to the StoreArray<Particle> and fills the ParticleLists.

The multiple ParticleLists with their own selection criteria are specified via list tuples (decayString, cut), for example

kaons = ('K+:mykaons', 'kaonID>0.1')
pions = ('pi+:mypions','pionID>0.1')
fillParticleLists([kaons, pions], path=mypath)


If you are unsure what selection you want, you might like to see the Standard Particles functions.

The type of the particles to be loaded is specified via the decayString module parameter. The type of the mdst dataobject that is used as an input is determined from the type of the particle. The following types of the particles can be loaded:

• charged final state particles (input mdst type = Tracks)
• e+, mu+, pi+, K+, p, deuteron (and charge conjugated particles)

• neutral final state particles
• “gamma” (input mdst type = ECLCluster)

• “K_S0”, “Lambda0” (input mdst type = V0)

• “K_L0” (input mdst type = KLMCluster or ECLCluster)

Note

For “K_S0” and “Lambda0” you must specify the daughter ordering.

For example, to load V0s as $$\Lambda^0\to p^+\pi^-$$ decays from V0s:

v0lambdas = ('Lambda0 -> p+ pi-', '0.9 < M < 1.3')
fillParticleLists([kaons, pions, v0lambdas], path=mypath)


Tip

Gammas can also be loaded from KLMClusters by explicitly setting the parameter loadPhotonsFromKLM to True. However, this should only be done in selected use-cases and the effect should be studied carefully.

Tip

For “K_L0” it is now possible to load from ECLClusters, to revert to the old (Belle) behavior, you can require 'isFromKLM > 0'.

klongs = ('K_L0', 'isFromKLM > 0')
fillParticleLists([kaons, pions, klongs], path=mypath)

Parameters
• decayStringsWithCuts (list) – A list of python ntuples of (decayString, cut). The decay string determines the type of Particle and the name of the ParticleList. If the input MDST type is V0 the whole decay chain needs to be specified, so that the user decides and controls the daughters ‘ order (e.g. K_S0 -> pi+ pi-) The cut is the selection criteria to be added to the ParticleList. It can be an empty string.

• writeOut (bool) – whether RootOutput module should save the created ParticleList

• path (basf2.Path) – modules are added to this path

• enforceFitHypothesis (bool) – If true, Particles will be created only for the tracks which have been fitted using a mass hypothesis of the exact type passed to fillParticleLists(). If enforceFitHypothesis is False (the default) the next closest fit hypothesis in terms of mass difference will be used if the fit using exact particle type is not available.

• loadPhotonsFromKLM (bool) – If true, photon candidates will be created from KLMClusters as well.

• loadPhotonBeamBackgroundMVA (bool) – If true, photon candidates will be assigned a beam background probability.

Creates Particle object for each MCParticle of the desired type found in the StoreArray<MCParticle>, loads them to the StoreArray<Particle> and fills the ParticleLists.

The types of the particles to be loaded are specified via the (decayString, cut) tuples given in a list. For example:

kaons = ('K+:gen', '')
pions = ('pi+:gen', 'pionID>0.1')
fillParticleListsFromMC([kaons, pions], path=mypath)

Parameters
• decayString – specifies type of Particles and determines the name of the ParticleList

• cut – Particles need to pass these selection criteria to be added to the ParticleList

• addDaughters – adds the bottom part of the decay chain of the particle to the datastore and sets mother-daughter relations

• skipNonPrimaryDaughters – if true, skip non primary daughters, useful to study final state daughter particles

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

modularAnalysis.fillSignalSideParticleList(outputListName, decayString, path)[source]

This function should only be used in the ROE path, that is a path that is executed for each ROE object in the DataStore.

Example: fillSignalSideParticleList(‘gamma:sig’,’B0 -> K*0 ^gamma’, roe_path)

Function will create a ParticleList with name ‘gamma:sig’ which will be filled with the existing photon Particle, being the second daughter of the B0 candidate to which the ROE object has to be related.

Parameters
• ouputListName – name of the created ParticleList

• decayString – specify Particle to be added to the ParticleList

modularAnalysis.findMCDecay(list_name, decay, writeOut=False, path=None)[source]

Warning

This function is not fully tested and maintained. Please consider to use reconstructMCDecay() instead.

Finds and creates a ParticleList for all MCParticle decays matching a given DecayString. The decay string is required to describe correctly what you want. In the case of inclusive decays, you can use Grammar for custom MCMatching

Parameters
• list_name – The output particle list name

• decay – The decay string which you want

• writeOut – Whether RootOutput module should save the created outputList

• path – modules are added to this path

modularAnalysis.getAnalysisGlobaltag(timeout=180)str[source]

Returns a string containing the name of the latest and recommended analysis globaltag.

Parameters

timeout – Seconds to wait for b2conditionsdb-recommend

modularAnalysis.getBeamBackgroundProbabilityMVA(particleList, path=None)[source]

Assign a probability to each ECL cluster as being background like (0) or signal like (1)

Parameters
• particleList – The input ParticleList, must be a photon list

• path – modules are added to this path

modularAnalysis.getNbarIDMVA(particleList, path=None)[source]

This function can give a score to predict if it is a anti-n0. It is not used to predict n0. Currently, this can be used only for ECL cluster. output will be stored in extraInfo(nbarID); -1 means MVA invalid

Parameters
• particleList – The input ParticleList

• path – modules are added to this path

modularAnalysis.inclusiveBtagReconstruction(upsilon_list_name, bsig_list_name, btag_list_name, input_lists_names, path)[source]

Reconstructs Btag from particles in given ParticleLists which do not share any final state particles (mdstSource) with Bsig.

Parameters
• upsilon_list_name – Name of the ParticleList to be filled with ‘Upsilon(4S) -> B:sig anti-B:tag’

• bsig_list_name – Name of the Bsig ParticleList

• btag_list_name – Name of the Bsig ParticleList

• input_lists_names – List of names of the ParticleLists which are used to reconstruct Btag from

modularAnalysis.inputMdst(environmentType, filename, path, skipNEvents=0, entrySequence=None, *, parentLevel=0, **kwargs)[source]

Loads the specified ROOT (DST/mDST/muDST) file with the RootInput module.

The correct environment (e.g. magnetic field settings) are determined from the specified environment type. For the possible values please see inputMdstList()

Parameters
• environmentType (str) – type of the environment to be loaded

• filename (str) – the name of the file to be loaded

• path (basf2.Path) – modules are added to this path

• skipNEvents (int) – N events of the input file are skipped

• entrySequence (str) – The number sequences (e.g. 23:42,101) defining the entries which are processed.

• parentLevel (int) – Number of generations of parent files (files used as input when creating a file) to be read

modularAnalysis.inputMdstList(environmentType, filelist, path, skipNEvents=0, entrySequences=None, *, parentLevel=0, useB2BIIDBCache=True)[source]

Loads the specified ROOT (DST/mDST/muDST) files with the RootInput module.

The correct environment (e.g. magnetic field settings) are determined from the specified environment type. The currently available environments are:

• ‘MC5’: for analysis of Belle II MC samples produced with releases prior to build-2016-05-01. This environment sets the constant magnetic field (B = 1.5 T)

• ‘MC6’: for analysis of Belle II MC samples produced with build-2016-05-01 or newer but prior to release-00-08-00

• ‘MC7’: for analysis of Belle II MC samples produced with build-2016-05-01 or newer but prior to release-00-08-00

• ‘MC8’, for analysis of Belle II MC samples produced with release-00-08-00 or newer but prior to release-02-00-00

• ‘MC9’, for analysis of Belle II MC samples produced with release-00-08-00 or newer but prior to release-02-00-00

• ‘MC10’, for analysis of Belle II MC samples produced with release-00-08-00 or newer but prior to release-02-00-00

• ‘default’: for analysis of Belle II MC samples produced with releases with release-02-00-00 or newer. This environment sets the default magnetic field (see geometry settings)

• ‘Belle’: for analysis of converted (or during of conversion of) Belle MC/DATA samples

• ‘None’: for analysis of generator level information or during simulation/reconstruction of previously generated events

Note that there is no difference between MC6 and MC7. Both are given for sake of completion. The same is true for MC8, MC9 and MC10

Parameters
• environmentType (str) – type of the environment to be loaded

• filelist (list(str)) – the filename list of files to be loaded

• path (basf2.Path) – modules are added to this path

• skipNEvents (int) – N events of the input files are skipped

• entrySequences (list(str)) – The number sequences (e.g. 23:42,101) defining the entries which are processed for each inputFileName.

• parentLevel (int) – Number of generations of parent files (files used as input when creating a file) to be read

• useB2BIIDBCache (bool) – Loading of local KEKCC database (only to be deactivated in very special cases)

This function is used to apply particle list specific cuts on one or more ROE masks (track or eclCluster). With this function one can KEEP the tracks/eclclusters used in particles from provided particle list. This function should be executed only in the for_each roe path for the current ROE object.

To avoid unnecessary computation, the input particle list should only contain particles from ROE (use cut ‘isInRestOfEvent == 1’). To update the ECLCluster masks, the input particle list should be a photon particle list (e.g. ‘gamma:someLabel’). To update the Track masks, the input particle list should be a charged pion particle list (e.g. ‘pi+:someLabel’).

Updating a non-existing mask will create a new one.

• keep only those tracks that were used in provided particle list

keepInROEMasks('pi+:goodTracks', 'mask', '', path=mypath)

• keep only those clusters that were used in provided particle list and pass a cut, apply to several masks

keepInROEMasks('gamma:goodClusters', ['mask1', 'mask2'], 'E > 0.1', path=mypath)

Parameters
• list_name – name of the input ParticleList

• cut_string – decay string with which the mask will be updated

• path – modules are added to this path

modularAnalysis.labelTauPairMC(printDecayInfo=False, path=None, TauolaBelle=False, mapping_minus=None, mapping_plus=None)[source]

Search tau leptons into the MC information of the event. If confirms it’s a generated tau pair decay, labels the decay generated of the positive and negative leptons using the ID of KKMC tau decay table.

Parameters
• printDecayInfo – If true, prints ID and prong of each tau lepton in the event.

• path – module is added to this path

• TauolaBelle – if False, TauDecayMarker is set. If True, TauDecayMode is set.

• mapping_minus – if None, the map is the default one, else the path for the map is given by the user for tau-

• mapping_plus – if None, the map is the default one, else the path for the map is given by the user for tau+

Loads Gearbox module to the path.

Warning

Should be used in a job with cosmic event generation only

Needed for scripts which only generate cosmic events in order to load the geometry.

Parameters
• path – modules are added to this path

• silence_warning – stops a verbose warning message if you know you want to use this function

modularAnalysis.looseMCTruth(list_name, path)[source]

Performs loose MC matching for all particles in the specified ParticleList. The difference between loose and normal mc matching algorithm is that the loose algorithm will find the common mother of the majority of daughter particles while the normal algorithm finds the common mother of all daughters. The results of loose mc matching algorithm are stored to the following extraInfo items:

• looseMCMotherPDG: PDG code of most common mother

• looseMCMotherIndex: 1-based StoreArray<MCParticle> index of most common mother

• looseMCWrongDaughterN: number of daughters that don’t originate from the most

common mother

• looseMCWrongDaughterPDG: PDG code of the daughter that doesn’t originate from

the most common mother (only if looseMCWrongDaughterN = 1)

• looseMCWrongDaughterBiB: 1 if the wrong daughter is Beam Induced Background

Particle

Parameters
• list_name – name of the input ParticleList

• path – modules are added to this path

modularAnalysis.markDuplicate(particleList, prioritiseV0, path)[source]

Call DuplicateVertexMarker to find duplicate particles in a list and flag the ones that should be kept

Parameters
• particleList – input particle list

• prioritiseV0 – if true, give V0s a higher priority

modularAnalysis.matchMCTruth(list_name, path)[source]

Performs MC matching (sets relation Particle->MCParticle) for all particles (and its (grand)^N-daughter particles) in the specified ParticleList.

Parameters
• list_name – name of the input ParticleList

• path – modules are added to this path

modularAnalysis.mergeListsWithBestDuplicate(outputListName, inputListNames, variable, preferLowest=True, writeOut=False, path=None)[source]

Merge input ParticleLists into one output ParticleList. Only the best among duplicates is kept. The lowest or highest value (configurable via preferLowest) of the provided variable determines which duplicate is the best.

Parameters
• ouputListName – name of merged ParticleList

• inputListName – vector of original ParticleLists to be merged

• variable – variable to determine best duplicate

• preferLowest – whether lowest or highest value of variable should be preferred

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

Give pi0/eta probability for hard photon.

In the default weight files a value of 1.4 GeV is set as the lower limit for the hard photon energy in the CMS frame.

The current default weight files are optimised using MC9. The input variables are as below. Aliases are set to some variables during training.

• M: pi0/eta candidates Invariant mass

• lowE: soft photon energy in lab frame

• cTheta: soft photon ECL cluster’s polar angle

• Zmva: soft photon output of MVA using Zernike moments of the cluster

• minC2Hdist: soft photon distance from eclCluster to nearest point on nearest Helix at the ECL cylindrical radius

Note

Please don’t use following ParticleList names elsewhere:

gamma:HARDPHOTON, pi0:PI0VETO, eta:ETAVETO, gamma:PI0SOFT + str(PI0ETAVETO_COUNTER), gamma:ETASOFT + str(PI0ETAVETO_COUNTER)

Please don’t use lowE, cTheta, Zmva, minC2Hdist as alias elsewhere.

Parameters
• particleList – The input ParticleList

• decayString – specify Particle to be added to the ParticleList

• workingDirectory – The weight file directory

• pi0vetoname – extraInfo name of pi0 probability

• etavetoname – extraInfo name of eta probability

• selection – Selection criteria that Particle needs meet in order for for_each ROE path to continue

• path – modules are added to this path

This function is used to apply particle list specific cuts on one or more ROE masks for Tracks. It is possible to optimize the ROE selection by treating tracks from V0’s separately, meaning, taking V0’s 4-momentum into account instead of 4-momenta of tracks. A cut for only specific V0’s passing it can be applied.

The input particle list should be a V0 particle list: K_S0 (‘K_S0:someLabel’, ‘’), Lambda (‘Lambda:someLabel’, ‘’) or converted photons (‘gamma:someLabel’).

Updating a non-existing mask will create a new one.

• treat tracks from K_S0 inside mass window separately, replace track momenta with K_S0 momentum

optimizeROEWithV0('K_S0:opt', 'mask', '0.450 < M < 0.550', path=mypath)

Parameters
• list_name – name of the input ParticleList

• cut_string – decay string with which the mask will be updated

• path – modules are added to this path

modularAnalysis.outputIndex(filename, path, includeArrays=None, keepParents=False, mc=True)[source]

Write out all particle lists as an index file to be reprocessed using parentLevel flag. Additional branches necessary for file to be read are automatically included. Additional Store Arrays and Relations to be stored can be specified via includeArrays list argument.

Parameters
• str – filename the name of the output index file

• str – path modules are added to this path

• list(str) – includeArrays: datastore arrays/objects to write to the output file in addition to particle lists and related information

• bool – keepParents whether the parents of the input event will be saved as the parents of the same event in the output index file. Useful if you are only adding more information to another index file

• bool – mc whether the input data is MC or not

modularAnalysis.outputMdst(filename, path)[source]

Saves mDST (mini-Data Summary Tables) to the output root file.

Warning

This function is kept for backward-compatibility. Better to use mdst.add_mdst_output directly.

Save uDST (user-defined Data Summary Tables) = MDST + Particles + ParticleLists The charge-conjugate lists of those given in particleLists are also stored. Additional Store Arrays and Relations to be stored can be specified via includeArrays list argument.

Note

This does not reduce the amount of Particle objects saved, see udst.add_skimmed_udst_output for a function that does.

modularAnalysis.printDataStore(eventNumber=- 1, path=None)[source]

Prints the contents of DataStore in the first event (or a specific event number or all events). Will list all objects and arrays (including size).

The command line tool: b2file-size.

Parameters
• eventNumber (int) – Print the datastore only for this event. The default (-1) prints only the first event, 0 means print for all events (can produce large output)

• path (basf2.Path) – the PrintCollections module is added to this path

Warning

This will print a lot of output if you print it for all events and process many events.

modularAnalysis.printList(list_name, full, path)[source]

Prints the size and executes Particle->print() (if full=True) method for all Particles in given ParticleList. For debugging purposes.

Parameters
• list_name – input ParticleList name

• full – execute Particle->print() method for all Particles

• path – modules are added to this path

modularAnalysis.printMCParticles(onlyPrimaries=False, maxLevel=- 1, path=None, *, showProperties=False, showMomenta=False, showVertices=False, showStatus=False)[source]

Prints all MCParticles or just primary MCParticles up to specified level. -1 means no limit.

By default this will print a tree of just the particle names and their pdg codes in the event, for example

[INFO] Content of MCParticle list
╰── Upsilon(4S) (300553)
├── B+ (521)
│   ├── anti-D_0*0 (-10421)
│   │   ├── D- (-411)
│   │   │   ├── K*- (-323)
│   │   │   │   ├── anti-K0 (-311)
│   │   │   │   │   ╰── K_S0 (310)
│   │   │   │   │       ├── pi+ (211)
│   │   │   │   │       │   ╰╶╶ p+ (2212)
│   │   │   │   │       ╰── pi- (-211)
│   │   │   │   │           ├╶╶ e- (11)
│   │   │   │   │           ├╶╶ n0 (2112)
│   │   │   │   │           ├╶╶ n0 (2112)
│   │   │   │   │           ╰╶╶ n0 (2112)
│   │   │   │   ╰── pi- (-211)
│   │   │   │       ├╶╶ anti-nu_mu (-14)
│   │   │   │       ╰╶╶ mu- (13)
│   │   │   │           ├╶╶ nu_mu (14)
│   │   │   │           ├╶╶ anti-nu_e (-12)
│   │   │   │           ╰╶╶ e- (11)
│   │   │   ╰── K_S0 (310)
│   │   │       ├── pi0 (111)
│   │   │       │   ├── gamma (22)
│   │   │       │   ╰── gamma (22)
│   │   │       ╰── pi0 (111)
│   │   │           ├── gamma (22)
│   │   │           ╰── gamma (22)
│   │   ╰── pi+ (211)
│   ├── mu+ (-13)
│   │   ├╶╶ anti-nu_mu (-14)
│   │   ├╶╶ nu_e (12)
│   │   ╰╶╶ e+ (-11)
│   ├── nu_mu (14)
│   ╰── gamma (22)
...


There’s a distinction between primary and secondary particles. Primary particles are the ones created by the physics generator while secondary particles are ones generated by the simulation of the detector interaction.

Secondaries are indicated with a dashed line leading to the particle name and if the output is to the terminal they will be printed in red. If onlyPrimaries is True they will not be included in the tree.

On demand, extra information on all the particles can be displayed by enabling any of the showProperties, showMomenta, showVertices and showStatus flags. Enabling all of them will look like this:

...
╰── pi- (-211)
│ p=(0.257, -0.335, 0.0238) |p|=0.423
│ production vertex=(0.113, -0.0531, 0.0156), time=0.00589
│ status flags=PrimaryParticle, StableInGenerator, StoppedInDetector
│ list index=48
│
╰╶╶ n0 (2112)
p=(-0.000238, -0.0127, 0.0116) |p|=0.0172
production vertex=(144, 21.9, -1.29), time=39
status flags=StoppedInDetector
list index=66


The first line of extra information is enabled by showProperties, the second line by showMomenta, the third line by showVertices and the last two lines by showStatus. Note that all values are given in Belle II standard units, that is GeV, centimeter and nanoseconds.

The depth of the tree can be limited with the maxLevel argument: If it’s bigger than zero it will limit the tree to the given number of generations. A visual indicator will be added after each particle which would have additional daughters that are skipped due to this limit. An example event with maxLevel=3 is given below. In this case only the tau neutrino and the pion don’t have additional daughters.

[INFO] Content of MCParticle list
╰── Upsilon(4S) (300553)
├── B+ (521)
│   ├── anti-D*0 (-423) → …
│   ├── tau+ (-15) → …
│   ╰── nu_tau (16)
╰── B- (-521)
├── D*0 (423) → …
├── K*- (-323) → …
├── K*+ (323) → …
╰── pi- (-211)

Parameters
• onlyPrimaries (bool) – If True show only primary particles, that is particles coming from the generator and not created by the simulation.

• maxLevel (int) – If 0 or less print the whole tree, otherwise stop after n generations

• showProperties (bool) – If True show mass, energy and charge of the particles

• showMomenta (bool) – if True show the momenta of the particles

• showVertices (bool) – if True show production vertex and production time of all particles

• showStatus (bool) – if True show some status information on the particles. For secondary particles this includes creation process.

modularAnalysis.printPrimaryMCParticles(path, **kwargs)[source]

Prints all primary MCParticles, that is particles from the physics generator and not particles created by the simulation

This is equivalent to printMCParticles(onlyPrimaries=True, path=path) and additional keyword arguments are just forwarded to that function

This function prints out the information for the current ROE, so it should only be used in the for_each path. It prints out basic ROE object info.

If mask names are provided, specific information for those masks will be printed out.

It is also possible to print out all particles in a given mask if the ‘full_print’ is set to True.

Parameters

• unpackComposites – if true, replace composite particles by their daughters

• full_print – print out particles in mask

• path – modules are added to this path

modularAnalysis.printVariableValues(list_name, var_names, path)[source]

Prints out values of specified variables of all Particles included in given ParticleList. For debugging purposes.

Parameters
• list_name – input ParticleList name

• var_names – vector of variable names to be printed

• path – modules are added to this path

modularAnalysis.rankByHighest(particleList, variable, numBest=0, outputVariable='', allowMultiRank=False, cut='', path=None)[source]

Ranks particles in the input list by the given variable (highest to lowest), and stores an integer rank for each Particle in an extraInfo field ${variable}_rank starting at 1 (best). The list is also sorted from best to worst candidate (each charge, e.g. B+/B-, separately). This can be used to perform a best candidate selection by cutting on the corresponding rank value, or by specifying a non-zero value for ‘numBest’. Tip Extra-info fields can be accessed by the extraInfo metavariable. These variable names can become clunky, so it’s probably a good idea to set an alias. For example if you rank your B candidates by momentum, rankByHighest("B0:myCandidates", "p", path=mypath) vm.addAlias("momentumRank", "extraInfo(p_rank)")  Parameters • particleList – The input ParticleList • variable – Variable to order Particles by. • numBest – If not zero, only the$numBest Particles in particleList with rank <= numBest are kept.

• outputVariable – Name for the variable that will be created which contains the rank, Default is ‘${variable}_rank’. • allowMultiRank – If true, candidates with the same value will get the same rank. • cut – Only candidates passing the cut will be ranked. The others will have rank -1 • path – modules are added to this path modularAnalysis.rankByLowest(particleList, variable, numBest=0, outputVariable='', allowMultiRank=False, cut='', path=None)[source] Ranks particles in the input list by the given variable (lowest to highest), and stores an integer rank for each Particle in an extraInfo field ${variable}_rank starting at 1 (best). The list is also sorted from best to worst candidate (each charge, e.g. B+/B-, separately). This can be used to perform a best candidate selection by cutting on the corresponding rank value, or by specifying a non-zero value for ‘numBest’.

Tip

Extra-info fields can be accessed by the extraInfo metavariable. These variable names can become clunky, so it’s probably a good idea to set an alias. For example if you rank your B candidates by dM,

rankByLowest("B0:myCandidates", "dM", path=mypath)

Parameters
• particleList – The input ParticleList

• variable – Variable to order Particles by.

• numBest – If not zero, only the $numBest Particles in particleList with rank <= numBest are kept. • outputVariable – Name for the variable that will be created which contains the rank, Default is ‘${variable}_rank’.

• allowMultiRank – If true, candidates with the same value will get the same rank.

• cut – Only candidates passing the cut will be ranked. The others will have rank -1

• path – modules are added to this path

modularAnalysis.reconstructDecay(decayString, cut, dmID=0, writeOut=False, path=None, candidate_limit=None, ignoreIfTooManyCandidates=True, chargeConjugation=True, allowChargeViolation=False)[source]

Creates new Particles by making combinations of existing Particles - it reconstructs unstable particles via their specified decay mode, e.g. in form of a DecayString: D0 -> K- pi+ or B+ -> anti-D0 pi+, … All possible combinations are created (particles are used only once per candidate) and combinations that pass the specified selection criteria are saved to a newly created (mother) ParticleList. By default the charge conjugated decay is reconstructed as well (meaning that the charge conjugated mother list is created as well) but this can be deactivated.

One can use an @-sign to mark a particle as unspecified for inclusive analyses, e.g. in a DecayString: '@Xsd -> K+ pi-'.

Warning

The input ParticleLists are typically ordered according to the upstream reconstruction algorithm. Therefore, if you combine two or more identical particles in the decay chain you should not expect to see the same distribution for the daughter kinematics as they may be sorted by geometry, momentum etc.

For example, in the decay D0 -> pi0 pi0 the momentum distributions of the two pi0 s are not identical. This can be solved by manually randomising the lists before combining.

Parameters
• decayStringDecayString specifying what kind of the decay should be reconstructed (from the DecayString the mother and daughter ParticleLists are determined)

• cut – created (mother) Particles are added to the mother ParticleList if they pass give cuts (in VariableManager style) and rejected otherwise

• dmID – user specified decay mode identifier

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

• candidate_limit – Maximum amount of candidates to be reconstructed. If the number of candidates is exceeded a Warning will be printed. By default, all these candidates will be removed and event will be ignored. This behaviour can be changed by 'ignoreIfTooManyCandidates' flag. If no value is given the amount is limited to a sensible default. A value <=0 will disable this limit and can cause huge memory amounts so be careful.

• ignoreIfTooManyCandidates – whether event should be ignored or not if number of reconstructed candidates reaches limit. If event is ignored, no candidates are reconstructed, otherwise, number of candidates in candidate_limit is reconstructed.

• chargeConjugation – boolean to decide whether charge conjugated mode should be reconstructed as well (on by default)

• allowChargeViolation – whether the decay string needs to conserve the electric charge

modularAnalysis.reconstructMCDecay(decayString, cut, dmID=0, writeOut=False, path=None, chargeConjugation=True)[source]

Finds and creates a ParticleList from given decay string. ParticleList of daughters with sub-decay is created.

Only signal particle, which means isSignal is equal to 1, is stored. One can use the decay string grammar to change the behavior of isSignal. One can find detailed information in DecayString.

Tip

If one uses same sub-decay twice, same particles are registered to a ParticleList. For example, K_S0:pi0pi0 =direct=> [pi0:gg =direct=> gamma:MC gamma:MC] [pi0:gg =direct=> gamma:MC gamma:MC]. One can skip the second sub-decay, K_S0:pi0pi0 =direct=> [pi0:gg =direct=> gamma:MC gamma:MC] pi0:gg.

Parameters
• decayStringDecayString specifying what kind of the decay should be reconstructed (from the DecayString the mother and daughter ParticleLists are determined)

• cut – created (mother) Particles are added to the mother ParticleList if they pass given cuts (in VariableManager style) and rejected otherwise isSignal==1 is always required by default.

• dmID – user specified decay mode identifier

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

• chargeConjugation – boolean to decide whether charge conjugated mode should be reconstructed as well (on by default)

modularAnalysis.reconstructMissingKlongDecayExpert(decayString, cut, dmID=0, writeOut=False, path=None, recoList='_reco')[source]

Creates a list of K_L0’s with their momentum determined from kinematic constraints of B->K_L0 + something else.

Parameters
• decayString – DecayString specifying what kind of the decay should be reconstructed (from the DecayString the mother and daughter ParticleLists are determined)

• cut – Particles are added to the K_L0 ParticleList if they pass the given cuts (in VariableManager style) and rejected otherwise

• dmID – user specified decay mode identifier

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

• recoList – suffix appended to original K_L0 ParticleList that identifies the newly created K_L0 list

modularAnalysis.reconstructRecoil(decayString, cut, dmID=0, writeOut=False, path=None, candidate_limit=None, allowChargeViolation=False)[source]

Creates new Particles that recoil against the input particles.

For example the decay string M -> D1 D2 D3 will:
• create mother Particle M for each unique combination of D1, D2, D3 Particles

• Particles D1, D2, D3 will be appended as daughters to M

• the 4-momentum of the mother Particle M is given by

p(M) = p(HER) + p(LER) - Sum_i p(Di)

Parameters
• decayString – DecayString specifying what kind of the decay should be reconstructed (from the DecayString the mother and daughter ParticleLists are determined)

• cut – created (mother) Particles are added to the mother ParticleList if they pass give cuts (in VariableManager style) and rejected otherwise

• dmID – user specified decay mode identifier

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

• candidate_limit – Maximum amount of candidates to be reconstructed. If the number of candidates is exceeded no candidate will be reconstructed for that event and a Warning will be printed. If no value is given the amount is limited to a sensible default. A value <=0 will disable this limit and can cause huge memory amounts so be careful.

• allowChargeViolation – whether the decay string needs to conserve the electric charge

modularAnalysis.reconstructRecoilDaughter(decayString, cut, dmID=0, writeOut=False, path=None, candidate_limit=None, allowChargeViolation=False)[source]

Creates new Particles that are daughters of the particle reconstructed in the recoil (always assumed to be the first daughter).

For example the decay string M -> D1 D2 D3 will:
• create mother Particle M for each unique combination of D1, D2, D3 Particles

• Particles D1, D2, D3 will be appended as daughters to M

• the 4-momentum of the mother Particle M is given by

p(M) = p(D1) - Sum_i p(Di), where i>1

Parameters
• decayString – DecayString specifying what kind of the decay should be reconstructed (from the DecayString the mother and daughter ParticleLists are determined)

• cut – created (mother) Particles are added to the mother ParticleList if they pass give cuts (in VariableManager style) and rejected otherwise

• dmID – user specified decay mode identifier

• writeOut – whether RootOutput module should save the created ParticleList

• path – modules are added to this path

• candidate_limit – Maximum amount of candidates to be reconstructed. If the number of candidates is exceeded no candidate will be reconstructed for that event and a Warning will be printed. If no value is given the amount is limited to a sensible default. A value <=0 will disable this limit and can cause huge memory amounts so be careful.

• allowChargeViolation – whether the decay string needs to conserve the electric charge taking into account that the first daughter is actually the mother

modularAnalysis.removeExtraInfo(particleLists=None, removeEventExtraInfo=False, path=None)[source]

Removes the ExtraInfo of the given particleLists. If specified (removeEventExtraInfo = True) also the EventExtraInfo is removed.

modularAnalysis.removeParticlesNotInLists(lists_to_keep, path)[source]

Removes all Particles that are not in a given list of ParticleLists (or daughters of those). All relations from/to Particles, daughter indices, and other ParticleLists are fixed.

Parameters
• lists_to_keep – Keep the Particles and their daughters in these ParticleLists.

• path – modules are added to this path

modularAnalysis.removeTracksForTrackingEfficiencyCalculation(inputListNames, fraction, path=None)[source]

Randomly remove tracks from the provided particle lists to estimate the tracking efficiency. Takes care of the duplicates, if any.

Parameters
• inputListNames (list(str)) – input particle list names

• fraction (float) – fraction of particles to be removed randomly

• path (basf2.Path) – module is added to this path

modularAnalysis.replaceMass(replacerName, particleLists=None, pdgCode=22, path=None)[source]

replaces the mass of the particles inside the given particleLists with the invariant mass of the particle corresponding to the given pdgCode.

Parameters
• particleLists – new ParticleList filled with copied Particles

• pdgCode – PDG code for mass reference

• path – modules are added to this path

modularAnalysis.scaleError(outputListName, inputListName, scaleFactors=[1.17, 1.12, 1.16, 1.15, 1.13], d0Resolution=[0.00122, 0.00141], z0Resolution=[0.00134, 0.00153], path=None)[source]

This module creates a new charged particle list. The helix errors of the new particles are scaled by constant factors. These scale factors are defined for each helix parameter (d0, phi0, omega, z0, tanlambda). The impact parameter resolution can be defined in a pseudo-momentum dependent form, which limits the d0 and z0 errors so that they do not shrink below the resolution. This module is supposed to be used for low-momentum (0-3 GeV/c) tracks in BBbar events. Details will be documented in a Belle II note by the Belle II Japan ICPV group.

Parameters
• inputListName – Name of input charged particle list to be scaled

• outputListName – Name of output charged particle list with scaled error

• scaleFactors – List of five constants to be multiplied to each of helix errors

• d0Resolution – List of two parameters, (a [cm], b [cm/(GeV/c)]), defining d0 resolution as sqrt{ a**2 + (b / (p*beta*sinTheta**1.5))**2 }

• z0Resolution – List of two parameters, (a [cm], b [cm/(GeV/c)]), defining z0 resolution as sqrt{ a**2 + (b / (p*beta*sinTheta**2.5))**2 }

modularAnalysis.scaleTrackMomenta(inputListNames, scale, path=None)[source]

Scale momenta of the particles according to the scaling factor scale. If the particle list contains composite particles, the momenta of the track-based daughters are scaled. Subsequently, the momentum of the mother particle is updated as well.

Parameters
• inputListNames (list(str)) – input particle list names

• scale (float) – scaling factor (1.0 – no scaling)

• path (basf2.Path) – module is added to this path

modularAnalysis.selectDaughters(particle_list_name, decay_string, path)[source]

Redefine the Daughters of a particle: select from decayString

Parameters
• particle_list_name – input particle list

• decay_string – for selecting the Daughters to be preserved

modularAnalysis.setAnalysisConfigParams(configParametersAndValues, path)[source]

Sets analysis configuration parameters.

These are:

• ‘tupleStyle’: ‘Default’ (default) or ‘Laconic’ o) defines the style of the branch name in the ntuple

• ‘mcMatchingVersion’: Specifies what version of mc matching algorithm is going to be used:

• ‘MC5’ - analysis of BelleII MC5

• ‘Belle’ - analysis of Belle MC

• ‘BelleII’ (default) - all other cases

Parameters
• configParametersAndValues – dictionary of parameters and their values of the form {param1: value, param2: value, …)

• modules – are added to this path

modularAnalysis.setupEventInfo(noEvents, path)[source]

Prepare to generate events. This function sets up the EventInfoSetter. You should call this before adding a generator from generators. The experiment and run numbers are set to 0 (run independent generic MC in phase 3). https://confluence.desy.de/display/BI/Experiment+numbering

Parameters
• noEvents (int) – number of events to be generated

• path (basf2.Path) – modules are added to this path

modularAnalysis.signalRegion(particleList, cut, path=None, name='isSignalRegion', blind_data=True)[source]

Define and blind a signal region. Per default, the defined signal region is cut out if ran on data. This function will provide a new variable ‘isSignalRegion’ as default, which is either 0 or 1 depending on the cut provided.

Example

ma.reconstructDecay("B+:sig -> D+ pi0", "Mbc>5.2", path=path)
ma.signalRegion("B+:sig",
"Mbc>5.27 and abs(deltaE)<0.2",
blind_data=True,
path=path)
ma.variablesToNtuples("B+:sig", ["isSignalRegion"], path=path)

Parameters
• particleList (str) – The input ParticleList

• cut (str) – Cut string describing the signal region

• path (basf2.Path) –

• name (str) – Name of the Signal region in the variable manager

• blind_data (bool) – Automatically exclude signal region from data

Checks if the current ROE object in the for_each roe path (argument roe_path) is related to the particle from the input ParticleList. Additional selection criteria can be applied. If ROE is not related to any of the Particles from ParticleList or the Particle doesn’t meet the selection criteria the execution of deadEndPath is started. This path, as the name suggests should be empty and its purpose is to end the execution of for_each roe path for the current ROE object.

Parameters
• particleList – The input ParticleList

• selection – Selection criteria that Particle needs meet in order for for_each ROE path to continue

• for_each – roe path in which this filter is executed

• deadEndPath – empty path that ends execution of or_each roe path for the current ROE object.

Checks if the current ROE object in the for_each roe path (argument roe_path) is related to the particle from the input ParticleList. Additional selection criteria can be applied. If ROE is not related to any of the Particles from ParticleList or the Particle doesn’t meet the selection criteria the execution of deadEndPath is started. This path, as the name suggests should be empty and its purpose is to end the execution of for_each roe path for the current ROE object.

Parameters
• particleLists – The input ParticleLists

• selection – Selection criteria that Particle needs meet in order for for_each ROE path to continue

• for_each – roe path in which this filter is executed

• deadEndPath – empty path that ends execution of or_each roe path for the current ROE object.

modularAnalysis.summaryOfLists(particleLists, outputFile=None, path=None)[source]

Prints out Particle statistics at the end of the job: number of events with at least one candidate, average number of candidates per event, etc. If an output file name is provided the statistics is also dumped into a json file with that name.

Parameters
• particleLists – list of input ParticleLists

• outputFile – output file name (not created by default)

modularAnalysis.tagCurlTracks(particleLists, mcTruth=False, responseCut=0.324, selectorType='cut', ptCut=0.6, train=False, path=None)[source]

Warning

The cut selector is not calibrated with Belle II data and should not be used without extensive study.

Identifies curl tracks and tags them with extraInfo(isCurl=1) for later removal. For Belle data with a B2BII analysis the available cut based selection is described in BN1079.

The module loops over all particles in a given list that meet the preselection ptCut and assigns them to bundles based on the response of the chosen selector and the required minimum response set by the responseCut. Once all particles are assigned they are ranked by 25dr^2+dz^2. All but the lowest are tagged with extraInfo(isCurl=1) to allow for later removal by cutting the list or removing these from ROE as applicable.

Parameters
• particleLists – list of particle lists to check for curls.

• mcTruth – bool flag to additionally assign particles with extraInfo(isTruthCurl) and extraInfo(truthBundleSize). To calculate these particles are assigned to bundles by their genParticleIndex then ranked and tagged as normal.

• responseCut – float min classifier response that considers two tracks to come from the same particle. Note ‘cut’ selector is binary 0/1.

• selectorType – string name of selector to use. The available options are ‘cut’ and ‘mva’. It is strongly recommended to used the ‘mva’ selection. The ‘cut’ selection is based on BN1079 and is only calibrated for Belle data.

• ptCut – pre-selection cut on transverse momentum.

• train – flag to set training mode if selector has a training mode (mva).

• path – module is added to this path.

Update an existing ROE mask by applying additional selection cuts for tracks and/or clusters.

See function appendROEMask!

Parameters
• list_name – name of the input ParticleList

• trackSelection – decay string for the track-based particles in ROE

• eclClusterSelection – decay string for the ECL-based particles in ROE

• klmClusterSelection – decay string for the KLM-based particles in ROE

• path – modules are added to this path

Update existing ROE masks by applying additional selection cuts for tracks and/or clusters.

The multiple ROE masks with their own selection criteria are specified via list tuples (mask_name, trackSelection, eclClusterSelection, klmClusterSelection)

See function appendROEMasks!

Parameters
• list_name – name of the input ParticleList

• path – modules are added to this path

modularAnalysis.updateROEUsingV0Lists(target_particle_list, mask_names, default_cleanup=True, selection_cuts=None, apply_mass_fit=False, fitter='treefit', path=None)[source]

This function creates V0 particle lists (photons, $$K^0_S$$ and $$\Lambda^0$$) and it uses V0 candidates to update the Rest Of Event, which is associated to the target particle list. It is possible to apply a standard or customized selection and mass fit to the V0 candidates.

Parameters
• target_particle_list – name of the input ParticleList

• default_cleanup – if True, predefined cuts will be applied on the V0 lists

• selection_cuts – a single string of selection cuts or tuple of three strings (photon_cuts, K_S0_cuts, Lambda0_cuts), which will be applied to the V0 lists. These cuts will have a priority over the default ones.

• apply_mass_fit – if True, a mass fit will be applied to the V0 particles

• fitter – string, that represent a fitter choice: “treefit” for TreeFitter and “kfit” for KFit

• path – modules are added to this path

modularAnalysis.variableToSignalSideExtraInfo(particleList, varToExtraInfo, path)[source]

Write the value of specified variables estimated for the single particle in the input list (has to contain exactly 1 particle) as an extra info to the particle related to current ROE. Should be used only in the for_each roe path.

Parameters
• particleList – The input ParticleList

• varToExtraInfo – Dictionary of Variables and extraInfo names.

• path – modules are added to this path

modularAnalysis.variablesToDaughterExtraInfo(particleList, decayString, variables, option=0, path=None)[source]

For each daughter particle specified via decay string the selected variables (estimated for the mother particle) are saved in an extra-info field with the given name. In other words, the property of mother is saved as extra-info to specified daughter particle.

An existing extra info with the same name will be overwritten if the new value is lower / will never be overwritten / will be overwritten if the new value is higher / will always be overwritten (-1/0/1/2).

Parameters
• particleList – The input ParticleList

• decayString – Decay string that specifies to which daughter the extra info should be appended

• variables – Dictionary of Variables and extraInfo names.

• option – Various options for overwriting

• path – modules are added to this path

modularAnalysis.variablesToEventExtraInfo(particleList, variables, option=0, path=None)[source]

For each particle in the input list the selected variables are saved in an event-extra-info field with the given name, Can be used to save MC truth information, for example, in a ntuple of reconstructed particles.

An existing extra info with the same name will be overwritten if the new value is lower / will never be overwritten / will be overwritten if the new value is higher / will always be overwritten (-1/0/1/2).

Parameters
• particleList – The input ParticleList

• variables – Dictionary of Variables and extraInfo names.

• path – modules are added to this path

modularAnalysis.variablesToExtraInfo(particleList, variables, option=0, path=None)[source]

For each particle in the input list the selected variables are saved in an extra-info field with the given name. Can be used when wanting to save variables before modifying them, e.g. when performing vertex fits.

An existing extra info with the same name will be overwritten if the new value is lower / will never be overwritten / will be overwritten if the new value is higher / will always be overwritten (-1/0/1/2).

Parameters
• particleList – The input ParticleList

• variables – Dictionary of Variables and extraInfo names.

• path – modules are added to this path

modularAnalysis.variablesToHistogram(decayString, variables, variables_2d=None, filename='ntuple.root', path=None, *, directory=None, prefixDecayString=False)[source]

Creates and fills a flat ntuple with the specified variables from the VariableManager

Parameters
• decayString (str) – specifies type of Particles and determines the name of the ParticleList

• variables (list(tuple))) – variables + binning which must be registered in the VariableManager

• variables_2d (list(tuple)) – pair of variables + binning for each which must be registered in the VariableManager

• filename (str) – which is used to store the variables

• path (basf2.Path) – the basf2 path where the analysis is processed

• directory (str) – directory inside the output file where the histograms should be saved. Useful if you want to have different histograms in the same file to separate them.

• prefixDecayString (bool) – If True the decayString will be prepended to the directory name to allow for more programmatic naming of the structure in the file.

modularAnalysis.variablesToNtuple(decayString, variables, treename='variables', filename='ntuple.root', path=None)[source]

Creates and fills a flat ntuple with the specified variables from the VariableManager. If a decayString is provided, then there will be one entry per candidate (for particle in list of candidates). If an empty decayString is provided, there will be one entry per event (useful for trigger studies, etc).

Parameters
• decayString (str) – specifies type of Particles and determines the name of the ParticleList

• variables (list(str)) – the list of variables (which must be registered in the VariableManager)

• treename (str) – name of the ntuple tree

• filename (str) – which is used to store the variables

• path (basf2.Path) – the basf2 path where the analysis is processed

Give pi0/eta probability for hard photon.

In the default weight files a value of 1.4 GeV is set as the lower limit for the hard photon energy in the CMS frame.

The current default weight files are optimised using MC12.

The input variables of the mva training are:

• M: pi0/eta candidates Invariant mass

• daughter(1,E): soft photon energy in lab frame

• daughter(1,clusterTheta): soft photon ECL cluster’s polar angle

• daughter(1,minC2TDist): soft photon distance from eclCluster to nearest point on nearest Helix at the ECL cylindrical radius

• daughter(1,clusterZernikeMVA): soft photon output of MVA using Zernike moments of the cluster

• daughter(1,clusterNHits): soft photon total crystal weights sum(w_i) with w_i<=1

• daughter(1,clusterE9E21): soft photon ratio of energies in inner 3x3 crystals and 5x5 crystals without corners

• cosHelicityAngleMomentum: pi0/eta candidates cosHelicityAngleMomentum

The following strings are available for mode:

• standard: loose energy cut and no clusterNHits cut are applied to soft photon

• tight: tight energy cut and no clusterNHits cut are applied to soft photon

• cluster: loose energy cut and clusterNHits cut are applied to soft photon

• both: tight energy cut and clusterNHits cut are applied to soft photon

The final probability of the pi0/eta veto is stored as an extraInfo. If no suffix is set it can be obtained from the variables pi0Prob/etaProb. Otherwise, it is available as ‘{Pi0, Eta}ProbOrigin’, ‘{Pi0, Eta}ProbTightEnergyThreshold’, ‘{Pi0, Eta}ProbLargeClusterSize’, or ‘{Pi0, Eta}ProbTightEnergyThresholdAndLargeClusterSize’} for the four modes described above, with the chosen suffix appended.

Note

Please don’t use following ParticleList names elsewhere:

gamma:HardPhoton, gamma:Pi0Soft + ListName + '_' + particleList.replace(':', '_'), gamma:EtaSoft + ListName + '_' + particleList.replace(':', '_'), pi0:EtaVeto + ListName, eta:EtaVeto + ListName

Parameters
• particleList – the input ParticleList

• decayString – specify Particle to be added to the ParticleList

• mode – choose one mode out of ‘standard’, ‘tight’, ‘cluster’ and ‘both’

• selection – selection criteria that Particle needs meet in order for for_each ROE path to continue

• path – modules are added to this path

• suffix – optional suffix to be appended to the usual extraInfo name

• hardParticle – particle name which is used to calculate the pi0/eta probability (default is gamma)

• pi0PayloadNameOverride – specify the payload name of pi0 veto only if one wants to use non-default one. (default is None)

• pi0SoftPhotonCutOverride – specify the soft photon selection criteria of pi0 veto only if one wants to use non-default one. (default is None)

• etaPayloadNameOverride – specify the payload name of eta veto only if one wants to use non-default one. (default is None)

• etaSoftPhotonCutOverride – specify the soft photon selection criteria of eta veto only if one wants to use non-default one. (default is None)